1

I am writing a tests for my LWC component using jest-cucumber. This is my test:

defineFeature(feature, test => {
  beforeEach(() => {
    
    element = createElement('c-myLwcElement', {
      is: myLwcElement,
    });
  })

}); 

but createElement (imported from 'lwc') is not working as expected. The element is created but connectedCallback is not called. In contrast, here is my generated jest test:

describe('c-myLwcElement', () => {
    afterEach(() => {
        // The jsdom instance is shared across test cases in a single file so reset the DOM
        while (document.body.firstChild) {
            document.body.removeChild(document.body.firstChild);
        }
    });

    it('TODO: test case generated by CLI command, please fill in test logic', async () => {
        // Arrange
        const element = createElement('c-myLwcElement', {
            is: Aggriddatatablev2qed,
        });

        element.objectApiName = 'Asset';

        // Act
        // document.body.appendChild(element);

        // Assert
        // const div = element.shadowRoot.querySelector('div');
        expect(1).toBe(1);
    });
});

Here, connectedCallback is called correctly for my component.

What is wrong with my setup in my jest-cucumber test?

1 Answer 1

1

The tag name should be in kebab case:

const element = createElement('c-my-lwc-element', {
    is: Aggriddatatablev2qed,
});

Also, make sure that Aggriddatatablev2qed is imported and extends LightningElement.

In addition, connectedCallback won't be called if you don't add it to the DOM:

// document.body.appendChild(element);

Should be:

document.body.appendChild(element);

Finally, before querying a child from the element, you have to wait a render cycle, which we typically do with Promise.resolve:

// Assert
await Promise.resolve();
const div = element.shadowRoot.querySelector('div');

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .