Make jest work in a project with at-sign imports
I added jest to an existing project and put a cover.test.js
files alongside the original cover.js
file.
We’re just testing pure JS functions here. Not components.
First gotcha is that the Getting Started docs don’t mention importing any jest functions, but I found that I needed to, to appease the IDE (if not the actual build-and-run). So pop these in your file:
import { test, expect, describe } from "@jest/globals";
Second gotcha was that every test run came back with some error like:
Cannot find module '@/common/cover' from 'src/common/cover.test.js'
Alright… so the test file can’t follow the at-sign reference to the code under test. No problem, I’ll rewrite the imports using dots…
But if I amended the import paths in the test.js
files to relative paths starting with dot instead of @, I got the same error one level deeper (where the code under test is importing some other dependency):
Cannot find module '@/constants/common.constants' from 'src/common/cover.js'
This made me think “Ok, jest is not running in the ‘use @ for root’ scope which the rest of the program knows to use”.
We’re running vue-cli so I considered adding a vue-cli testing add-on, but thanks to my skepticism about adding big packages, I did some more searching and settled on a piece of jest config:
module.exports = {
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
},
};
…which became my jest.config.js
in the root of the project. And that sorts it.
This is equivalent to a bit of jsconfig
that we have, which goes:
{
"compilerOptions": {
"module": "ESNext",
...
"paths": {
"@/*": [
"./src/*"
]
},
Both piece of config map @/**
to /src/**
in their own special way.
After the jest config fix, I could now get my tests to pass, even with @-style references in the test code.
As always, I hope it helps you if you ended up here by Goog/Duck/Marginalia.
First post of the year 2025! Let the blogging energy flow… ⚡🔖