3

I'm trying to write a unit test for my open source LWC but cannot complete the test as the createElement member from the LWC package no longer exists. I have been following the docs on lwc.dev but they seem to be outdated and still using createElement in their example.

I have a TypeScript-enabled LWR application and I have installed jest, jest-environment-jsdom, @types/jest and @lwc/jest-preset.

Here is my component:

// hello.html
<template>
  <h1>Hello, {greeting}!<h1>
<template>
// hello.ts
import { LightningElement } from 'lwc';

export default class Hello extends LightningElement {
  greeting = 'World';
}

And here is my unit test:

// __tests__/hello.test.ts
import { createElement } from 'lwc';
import Hello from '../hello';

describe('hello', () => {
  afterEach(() => {
    while (document.body.firstChild) {
      document.body.removeChild(document.body.firstChild);
    }
  });
  
  it('renders greeting', () => {
    const element = createElement('tut-hello', {
      is: Hello
    });
    document.body.appendChild(element);
    const div = element.shadowRoot.querySelector('div');
    expect(div.textContent).toBe('Hello, World!');
  });
});

VS Code is showing me an error line under createElement in my import statement:

Module '"lwc"' has no exported member 'createElement'.ts(2305).

When I run the test I get a failure with the following message:

TypeError: Cannot read properties of null (reading 'textContent').

All LWC examples I could find use createElement yet there are GitHub PRs from years ago with comments saying that createElement api will soon be deprecated.

The only other way I could find to possibly create an element is from a comment in the base LightningComponent class within the framework itself:

customElements.define('tut-hello', Hello.CustomElementConstructor);
const element = document.createElement('tut-hello', { 
  is: 'tut-hello' 
});

But this doesn't work for me either. How do I create an element for testing with the latest version of LWC OSS?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.