I have two components that are in my app:
- parentComponent
- childComponent.
'parentComponent' includes 'childComponent' as a component.
E.g: parentComponent.html
<template>
<c-child-component
child-property={aValue}
other-child-property={anotherValue}
></c-child-component>
</template>
Child component is non-trivial, and maybe includes some @wire
methods or imperative calls to Apex.
Therefore, when writing the Jest unit test for parentComponent
we want to mock childComponent
so we don't have to worry about its complex behaviour – particularly when it references the database.
The Salesforce documentation (at time of writing) describes mocking LWCs in both the following links:
- https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.unit_testing_using_jest_patterns
- https://trailhead.salesforce.com/content/learn/modules/test-lightning-web-components/mock-other-components
This involves creating a jest.config.js
file and defining moduleNameMapper
references.
Unfortuantely, this will change the behaviour of the import so that it includes the mock version in all tests.
In the described situation, we have build childComponent
and therefore need to also test this component – and so we can't use that technique.
So – How can I mock childComponent
only in the unit test for parentComponent
?
Best Answer
In order to mock
childComponent
only in the test forparentComponent
we need to:childComponent
as a JS file.parentComponent
test to use this file instead of the realchildComponent
.Build a skeleton stub for
childComponent
as a JS file.childComponent
's folder named__mocks__
.childComponent.js
, copying the contents of the real component into it. You should end up with a folder structure like:@api
defined properties. E.g:**/__mocks__/**
into your .forceignore. E.g. it may look like:Instruct the
parentComponent
test to use this file instead of the realchildComponent
.parentComponent
, tell Jest to use the mock version ofchildComponent
by callingjest.mock
passing the Salesforce style import path of the component. E.g. the top of your test file may look like:Stretch goal: Mocking methods that exist on the child component.
For example:
Note: in general, I would use more identifying characteristics on the component other than simply the type of HTML element it is. E.g. I would add a data-id or data-name and use that instead.
(thanks to https://tigerfacesystems.com/blog/lwc-nested-component-testing for the basic solution to this problem)