0

How can I test if:true element in my lwc? showLoadingSpinner is @api. I am new to jest, sorry if stupid question. Console log shows null.

<template if:true={showLoadingSpinner}>
    <div id="spinner">
        <lightning-spinner class="slds-align_absolute-center" variant="brand" size="small" alternative-text="Loading.."></lightning-spinner>
    </div>
</template>

test.js

const element = createElement('c-pagerLwc', { is: page });
        document.body.appendChild(element);
        element.showLoadingSpinner = true;


        return Promise.resolve().then(() => {
            let spinner = document.querySelector('#spinner');
            console.log('spinner: ' + spinner);
            expect(spinner).not.toBeNull();
        });

1 Answer 1

1

you can write the jest test for conditional rendering as below. Some important things to considered:-

  • You need to import your component and use describe which creates a block that groups together several related tests.
  • afterEach Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing.
  • it - All you need in a test file is the test method which runs a test.
  • Expect - When you're writing tests, you often need to check that values meet certain conditions. expect gives you access to a number of "matchers" that let you validate different things.
  • A lot of examples are avialable in this github repository for lwc

I have just added the code when spinner does not exist in dom, You can add another test in test file for testing the positive scenario.


import { createElement } from 'lwc';
import HelloConditionalRendering from 'c/pagerLwc';

describe('c-pager-lwc', () => {
    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('does not show spinner by default', () => {
        // Create element
        const element = createElement('c-pager-lwc', {
            is: HelloConditionalRendering
        });
        document.body.appendChild(element);

        // Verify spinner exist
        const detailEl = element.shadowRoot.querySelector('lightning-spinner');
        expect(detailEl).toBe(null);
    });
});
1
  • Thank you, it works and git rep is awesome.
    – raholed
    Commented Sep 1, 2022 at 11:56

You must log in to answer this question.

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