3

How can I use Jest to test a LWC component where data is provided via @api annotation?
For example, I have a component unitTestComponent.js

import { LightningElement, api } from 'lwc';

export default class UnitTestComponent extends LightningElement {
    @api apiField;

    connectedCallback(){
        console.log(this.apiField.Name);

    }
}

Which I can use it like this

<c-unit-test-component api-field={testPayload}></c-unit-test-component>

Where testPayload is some JSON object, for example {Name: 'xxx'}
Now, I'm trying to write a sample test

import { createElement } from 'lwc';
import UnitTestComponent from 'c/unitTestComponent';

describe('c-unit-test-component', () => {
    afterEach(() => {
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    test('initialization', () => {
        const element = createElement('c-unit-test-component', {
            is: UnitTestComponent
        });
        document.body.appendChild(element);
        expect(1).toBe(1);
    });
});

This gives me an error TypeError: Cannot read property 'Name' of undefined. How can I provide some mock data in the test block?

1 Answer 1

4

You would provide the value yourself or else it'll be undefined.

test('initialization', () => {
        const element = createElement('c-unit-test-component', {
            is: UnitTestComponent
        });
        <!-- set @api variable -->
        element.apiField = {Name: 'test'}
        document.body.appendChild(element);

        return Promise.resolve().then(() => {
           <!-- do your assertion / expect -->
       });

    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.