referencing this answer:Mocking CurrentPageReference wire in Jest unit tests - LWC
This is how I mock CurrentPageReference in the test file , the navigate functionality seem to work but I can't call the setter for the currentPageReference in the actual component.
This is what my test looks like:
import {CurrentPageReference} from 'lightning/navigation';
const currentPageReferenceAdapter = registerTestWireAdapter(CurrentPageReference);
const createOnlineSalesHomePageDynamic = (params = {}) => {
const element = createElement(
'runtime_online_sales-online-sales-home-page',
{is: OnlineSalesHomePage}
);
Object.assign(element, params);
document.body.appendChild(element);
return element;
};
describe('Product catalog tests in onlineSalesHomePage', () => {
it('should show expected breadcrumb on contract detail navigation', () => {
const props = {
currentPageReferenceAdapter: currentPageReferenceAdapter,
};
const element = createOnlineSalesHomePageDynamic(props);
return Promise.resolve()
.then(() => {
// Navigate to Contract Details.. this works!
currentPageReferenceAdapter.emit(getPageReference(VIEW.CONTRACT_DETAIL, {c__id : contracts[0].contractId}));
})
.then(() => {
const bcElement = element.shadowRoot.querySelector('runtime_online_sales-breadcrumb');
debugger; // !! bcElement null, since currentPageReference for the actual component is not defined and that because the setter is never called
})
});
});
This is the code actual component where the currentPageReference is injected, but this never gets called in the test as I expect it to:
@wire(CurrentPageReference)
setCurrentPageReference(currentPageReference) {
debugger;
// ! never gets called through the unit test as I expect it to !
this.currentPageReference = currentPageReference;
// some other setter code
}
getPageReference() function:
export function getPageReference(view, state) {
const pageRef = {
type: 'standard__navItemPage',
attributes: {
apiName: 'standard-OnlineSalesHome',
},
state: {}
};
if (view !== VIEW.HOME) {
Object.assign(pageRef.state, {c__view: view});
}
if (state) {
Object.assign(pageRef.state, state);
}
return pageRef;
}
CurrentPageReference
? Ex. Load the page with certain parameters. If so, it sounds like it'd just be its own test....test1: navigate logic, test2: currentpagereference logic