0

The lightning/toast utility is GA as of Winter '24, but I haven't seen anything on StackExchange or in the docs about how to write tests for components that use it. One you import it into a component and try to run Jest tests, you get an error like this:

Cannot find module 'lightning/toast' from 'force-app/main/default/lwc/myApp/myApp.js'

I'm doing a Q&A-style entry here for posterity. The solution is simple enough if you know about mocking patterns in Jest + LWC, but I'm sure many devs will encounter this error, search Google for it, and end up here.

1 Answer 1

0

In keeping with the mocking approach suggested by the Lightning Web Components Tests Trailhead module, here are the steps:

  1. Create this directory in your SFDX repo if it doesn't already exist: force-app/test/jest-mocks/lightning
  2. Add a new file, toast.js, to the above directory. A very basic stub like this should work for most use cases:
export default class Toast {
  static show() {}
}
  1. Update the jest.config.js file in the root of your repo. Add or update the moduleNameMapper property of module.exports as follows to include a new property, ^lightning/toast$, pointing to the mock's file path:
...
module.exports = {
  ...
  moduleNameMapper: {
    "^lightning/toast$": "<rootDir>/force-app/test/jest-mocks/lightning/toast"
  }
};

Jest will now use the stub, and it will no longer complain about not being able to find lightning/toast.

You must log in to answer this question.

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