Code Transformation
Jest runs the code in your project as JavaScript, but if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates) then you'll need to transform that code into plain JavaScript, similar to what you would do when building for browsers.
Jest supports this via the transform
configuration option.
A transformer is a module that provides a method for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by Node, you might plug in a code preprocessor that would transpile a future version of JavaScript to a current one.
Jest will cache the result of a transformation and attempt to invalidate that result based on a number of factors, such as the source of the file being transformed and changing configuration.
Defaults
Jest ships with one transformer out of the box – babel-jest
. It will load your project's Babel configuration and transform any file matching the /\.[jt]sx?$/
RegExp (in other words, any .js
, .jsx
, .ts
or .tsx
file). In addition, babel-jest
will inject the Babel plugin necessary for mock hoisting talked about in ES Module mocking.
By default, babel-jest
includes babel-preset-jest
. You can disable this behavior by specifying excludeJestPreset: true
to babel-jest
. Note that this will also stop hoisting jest.mock
, which may break your tests.
"transform": {
"\\.[jt]sx?$": ["babel-jest", { "excludeJestPreset": true }],
}
Remember to include the default babel-jest
transformer explicitly, if you wish to use it alongside with additional code preprocessors:
"transform": {
"\\.[jt]sx?$": "babel-jest",
"\\.css$": "some-css-transformer",
}