We will use this Navigatemixin service to navigate to different pages in lightning web components. In this post, we will see how to cover this js method in JEST test class.
Navigatemixin used component: On clicking button, it will navigate to home page.
Cover Navigatemixin method in LWC using JEST testing
exNavigationMixinJest.html
<pre><code class="language-html"><?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="exTilejest">
<apiVersion>46.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle></code></pre>
exNavigationMixinJest.js
import { LightningElement } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class ExNavigationMixinJest extends NavigationMixin(LightningElement) {
navigateToHome() {
// Use the built-in 'Navigate' method
this[NavigationMixin.Navigate]({
// Pass in pageReference
type: 'standard__namedPage',
attributes: {
pageName: 'home'
},
});
}
}
exNavigationMixinJest.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="exNavigationMixinJest">
<apiVersion>46.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
exNavigationMixinJest.test.js
import { createElement } from 'lwc';
import exNavigationMixinJest from 'c/exNavigationMixinJest';
import { getNavigateCalledWith } from 'lightning/navigation';
describe('c-ex-navigation-mixin-jest', () => {
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);
}
// Prevent data saved on mocks from leaking between tests
jest.clearAllMocks();
});
it('navigates to home page on button clicked', () => {
const INPUT_PAGENAME = 'home';
const INPUT_TYPE = 'standard__namedPage';
// Create initial element
const element = createElement('c-ex-navigation-mixin-jest', {
is: exNavigationMixinJest
});
document.body.appendChild(element);
// Select button to simulate user interaction
const buttonEl = element.shadowRoot.querySelector('lightning-button');
buttonEl.click();
const { pageReference } = getNavigateCalledWith();
// Verify the component under test called the correct navigate event
expect(pageReference.type).toBe(INPUT_TYPE);
expect(pageReference.attributes.pageName).toBe(INPUT_PAGENAME);
});
})
Also found above code in Tech Shorts Git repo