1. path mapping

If you use “baseUrl” and “paths” options in your tsconfig file, you should make sure the “moduleNameMapper” option in your Jest config is setup accordingly.

ts-jest provides a helper to transform the mapping from tsconfig to Jest config format, but it needs the .js version of the config file.

2. sample here

With the below config in your tsconfig:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
"compilerOptions": {
"paths": {
"@App/*": ["src/*"],
"common/*": ["common/*"]
}
}
}

// jest.config.js
module.exports = {
// [...]
moduleNameMapper: {
'^@App/(.*)$': '<rootDir>/src/$1',
'^common/(.*)$': '<rootDir>/common/$1'
}
};

3. Handling Static Assets

Next, let’s configure Jest to gracefully handle asset files such as stylesheets and images. Usually, these files aren’t particularly useful in tests so we can safely mock them out. However, if you are using CSS Modules then it’s better to mock a proxy for your className lookups.

1
2
3
4
5
6
7
8
9
10
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/__mocks__/styleMock.js"
}

// __mocks__/styleMock.js
module.exports = {};

// __mocks__/fileMock.js
module.exports = 'test-file-stub';