jest: handling static assets with mocks

2021-01-16

 | 

~2 min read

 | 

387 words

Update: A previous version of this post tried to resolve an absolute path for the mocks. This doesn’t work out of the box, so I’ve updated it to be a relative path.

Webpack, because of its deep integration into an application, can create additional complexity when it comes to testing. Fortunately, Jest makes handling static assets (e.g., images and style sheets) relatively straight forward… once you understand how.

In its simplest form, handling static assets is a two-step process:

  1. Update the Jest config using a moduleNameMapper
  2. Create a mock file that will be referenced by the moduleNameMapper

Starting with the jest.config.js (the same thing could be accomplished if Jest is configured in the package.json):

jest.config.js
module.exports = {
    moduleNameMapper: {
        "\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": require.resolve(
            "./test/file-mock.js",
        ),
        "\\.(css|less)$": require.resolve("./test/style-mock.js"),
    },
}

With this done, Jest now understands to map any reference to a .css file to the style-mock.js in our test directory.

That file doesn’t exist yet. Let’s make it.

Since the purpose of this file is to enable Jest to move past the file by allowing it to understand how to handle the CSS file (in this case), the mock file can be quite simple:

test/style-mock.js
module.exports = {}

The file mock is very similar:

test/file-mock.js
module.exports = "test-file-stub"

With the mock files in place, when we run the Jest runner again, we should not see an “unexpected token” error1.

For more details on how to work with Webpack, the Jest team put together this document.

Footnotes

1 An example of this error looks like the following:

```
Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
    • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
    • If you need a custom transformation specify a "transform" option in your config.
    • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html
```

Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!