element.addEventListener(ShowToastEventName, handler) not functioning as expected in test
Russman12 opened this issue · comments
Summary
I'm trying to test that a toast is being displayed as expected for a component but the examples in the project to do not run properly. It appears lightning/platformShowToastEvent
is not importing as expected.
Steps To Reproduce
Attempt to run test displays a success toast after record creation
in \force-app\main\default\lwc\ldsCreateRecord
Current Behavior
Test fails on line 121
Expected Behavior
Test should pass
Relevant Log Output
Below is an example of the error I am receiving from the test execution:
c-lds-create-record › displays a success toast after record creation
expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls: 0
119 |
120 | // Check if toast event has been fired
> 121 | expect(handler).toHaveBeenCalled();
| ^
122 | expect(handler.mock.calls[0][0].detail.variant).toBe('success');
123 | });
124 |
at Object.<anonymous> (force-app/main/default/lwc/ldsCreateRecord/__tests__/ldsCreateRecord.test.js:121:9)
Additional Details
I have tried replacing the reference to ShowToastEventName
on line 104 with 'lightning__showtoast'
that fixes the initial error but then fails on the next line as there is no access to the event's properties.
I have investigated other tests but they all seem to follow this same pattern, which doesn't work. This has been tested using @salesforce/sfdx-lwc-jest 1.1.3.
Welcome! 👋
Thank you for posting this issue. 🙇🏼♂️ We will come back to you latest within the next 48h (working days). Stay tuned!
I was able to find a solution to my issue. The test in the recipe project was importing ShowToastEventName
from lightning/platformShowToastEvent
. I didn't realize that the recipe was actually overwriting this import with a custom ShowToastEvent
object defined in force-app/test/jest-mocks/lightning/platformShowToastEvent.js
and I didn't copy that file to my project.
In case anyone else has this same issue, here's how it was resolved for me.
- Copy the
ShowToastEvent
defined inforce-app/test/jest-mocks/lightning/platformShowToastEvent.js
to your project - add the following to jest.config.js => module.exports (see jest.config.js for an example):
moduleNameMapper: {
'^lightning/platformShowToastEvent$': '<rootDir>/force-app/test/jest-mocks/lightning/platformShowToastEvent',
},
I understand why this needs to be done but how it's done is confusing as there is nothing in the recipe that makes it apparent that this import is custom and overwriting the default import. Maybe some inline documentation can be added to classes which have overwritten imports like this?
Thank you for the feedback @Russman12. We will add more documentation to make it easier for developers to find the relevant jest mocks.