2

I have a function that is declared within my default class (constructor) that I would like to export to a Jest test suite. Is this possible?

testLWC.js

import { LightningElement } from 'lwc';

export default class JMRTestLWC extends LightningElement {
   sum(a, b) {
      return a + b;
   }
}

testLWC.test.js

import { sum } from 'c/jMRTestLWC'

describe('Addition Suite.', () => {
    test('Properly sum two numbers.', () => {
        const num = 1+2;
        expect(sum(1,2)).toBe(3);
    })
})

1 Answer 1

5

In order to use a method, you must expose it as a public method. I wrote a unit test using your code, and it ended up looking like this:


import { api, LightningElement } from 'lwc';

export default class Q361000 extends LightningElement {
    @api sum(a, b) {
        return a + b;
    }
}

import { createElement } from 'lwc';
import Q361000 from '../q361000';

describe('c-q361000', () =>{
    it('sums correctly', () =>{
        const element = createElement('c-q361000', { is: Q361000 });
        document.body.appendChild(element);
        expect(element.sum(1,2)).toBe(3);
    })
})
3
  • 3
    What's important here is that JEST sees LWC classes under test as black boxes and can only access the "API" of the LWC itself. This solution allows the testing by using @api, which makes the function as part of the "API". Everything else is internal and not accessible in the tests directly. That means JEST is great for testing the over-all behaviour of your LWC but not much help for directly unit testing internal functions etc.
    – Phil W
    Oct 31, 2021 at 18:20
  • 1
    Thank you for the clarification. It seems weird to have to create DOM elements just to unit test functions vs. a traditional application where I can just import the module. @sfdcfox/@Phil W, is there a way I could encapsulate the createElement() logic into a beforeAll() method to avoid re-writing this for each test case?
    – JMRiss
    Oct 31, 2021 at 19:54
  • @JMRiss Yes, you could choose to construct the element in beforeAll and tear it down in afterAll, if you desire. The engine doesn't do any extra work between each test unless you instruct it to.
    – sfdcfox
    Nov 1, 2021 at 1:06

You must log in to answer this question.

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