You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: CHANGELOG.md
+1Lines changed: 1 addition & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -43,6 +43,7 @@
43
43
-`[jest-runtime]`[**BREAKING**]`Runtime.createHasteMap` now returns a promise ([#12008](https://github.com/facebook/jest/pull/12008))
44
44
-`[jest-runtime]` Calling `jest.resetModules` function will clear FS and transform cache ([#12531](https://github.com/facebook/jest/pull/12531))
45
45
-`[@jest/schemas]` New module for JSON schemas for Jest's config ([#12384](https://github.com/facebook/jest/pull/12384))
46
+
-`[jest-transform]`[**BREAKING**] Make it required for `process()` and `processAsync()` methods to always return structured data ([#12638](https://github.com/facebook/jest/pull/12638))
46
47
-`[jest-test-result]` Add duration property to JSON test output ([#12518](https://github.com/facebook/jest/pull/12518))
47
48
-`[jest-watcher]`[**BREAKING**] Make `PatternPrompt` class to take `entityName` as third constructor parameter instead of `this._entityName` ([#12591](https://github.com/facebook/jest/pull/12591))
48
49
-`[jest-worker]`[**BREAKING**] Allow only absolute `workerPath` ([#12343](https://github.com/facebook/jest/pull/12343))
Copy file name to clipboardExpand all lines: docs/CodeTransformation.md
+34-12Lines changed: 34 additions & 12 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -3,29 +3,36 @@ id: code-transformation
3
3
title: Code Transformation
4
4
---
5
5
6
-
Jest runs the code in your project as JavaScript, but if you use some syntax not supported by Node.js out of the box (such as JSX, types from TypeScript, Vue templates etc.) then you'll need to transform that code into plain JavaScript, similar to what you would do when building for browsers.
6
+
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.
7
7
8
-
Jest supports this via the [`transform` configuration option](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object).
8
+
Jest supports this via the [`transform`](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object) configuration option.
9
9
10
-
A transformer is a module that provides a synchronous function 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 one of many compilers that compile a future version of JavaScript to a current one.
10
+
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.
11
11
12
12
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.
13
13
14
14
## Defaults
15
15
16
-
Jest ships with one transformer out of the box - `babel-jest`. It will automatically load your project's Babel configuration and transform any file matching the following RegEx: `/\.[jt]sx?$/`meaning any `.js`, `.jsx`, `.ts`and`.tsx` file. In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports).
16
+
Jest ships with one transformer out of the box –[`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). 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](ManualMocks.md#using-with-es-module-imports).
17
17
18
-
If you override the `transform` configuration option `babel-jest` will no longer be active, and you'll need to add it manually if you wish to use Babel.
18
+
:::tip
19
+
20
+
Remember to include the default `babel-jest` transformer explicitly, if you wish to use it alongside with additional code preprocessors:
21
+
22
+
```json
23
+
"transform": {
24
+
"\\.[jt]sx?$": "babel-jest",
25
+
"\\.css$": "some-css-transformer",
26
+
}
27
+
```
28
+
29
+
:::
19
30
20
31
## Writing custom transformers
21
32
22
33
You can write your own transformer. The API of a transformer is as follows:
23
34
24
35
```ts
25
-
// This version of the interface you are seeing on the website has been trimmed down for brevity
26
-
// For the full definition, see `packages/jest-transform/src/types.ts` in https://github.com/facebook/jest
27
-
// (taking care in choosing the right tag/commit for your version of Jest)
@@ -111,6 +123,12 @@ type TransformerFactory<X extends Transformer> = {
111
123
};
112
124
```
113
125
126
+
:::note
127
+
128
+
The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/facebook/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest).
129
+
130
+
:::
131
+
114
132
There are a couple of ways you can import code into Jest - using Common JS (`require`) or ECMAScript Modules (`import` - which exists in static and dynamic versions). Jest passes files through code transformation on demand (for instance when a `require` or `import` is evaluated). This process, also known as "transpilation", might happen _synchronously_ (in the case of `require`), or _asynchronously_ (in the case of `import` or `import()`, the latter of which also works from Common JS modules). For this reason, the interface exposes both pairs of methods for asynchronous and synchronous processes: `process{Async}` and `getCacheKey{Async}`. The latter is called to figure out if we need to call `process{Async}` at all. Since async transformation can happen synchronously without issue, it's possible for the async case to "fall back" to the sync variant, but not vice versa.
115
133
116
134
So if your code base is ESM only implementing the async variants is sufficient. Otherwise, if any code is loaded through `require` (including `createRequire` from within ESM), then you need to implement the synchronous variant. Be aware that `node_modules` is not transpiled with default config.
@@ -125,7 +143,9 @@ Note that [ECMAScript module](ECMAScriptModules.md) support is indicated by the
125
143
126
144
:::tip
127
145
128
-
Make sure `TransformedSource` contains a source map, so it is possible to report line information accurately in code coverage and test errors. Inline source maps also work but are slower.
146
+
Make sure `process{Async}` method returns source map alongside with transformed code, so it is possible to report line information accurately in code coverage and test errors. Inline source maps also work but are slower.
147
+
148
+
During the development of a transformer it can be useful to run Jest with `--no-cache` to frequently [delete cache](Troubleshooting.md#caching-issues).
129
149
130
150
:::
131
151
@@ -143,8 +163,10 @@ Importing images is a way to include them in your browser bundle, but they are n
Copy file name to clipboardExpand all lines: docs/Configuration.md
+12-13Lines changed: 12 additions & 13 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1564,27 +1564,26 @@ Default timeout of a test in milliseconds.
1564
1564
1565
1565
Default: `{"\\.[jt]sx?$": "babel-jest"}`
1566
1566
1567
-
A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function 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 one of many compilers that compile a future version of JavaScript to a current one. Example: see the [examples/typescript](https://github.com/facebook/jest/blob/main/examples/typescript/package.json#L16) example or the [webpack tutorial](Webpack.md).
1567
+
A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: `{filePattern: ['path-to-transformer', {options}]}`. For example, here is how you can configure `babel-jest` for non-default behavior: `{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}`.
1568
1568
1569
-
Examples of such compilers include:
1569
+
Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup) transformer, which 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](ManualMocks.md#using-with-es-module-imports).
1570
1570
1571
-
-[Babel](https://babeljs.io/)
1572
-
-[TypeScript](http://www.typescriptlang.org/)
1573
-
- To build your own please visit the [Custom Transformer](CodeTransformation.md#writing-custom-transformers) section
1574
-
1575
-
You can pass configuration to a transformer like `{filePattern: ['path-to-transformer', {options}]}` For example, to configure babel-jest for non-default behavior, `{"\\.js$": ['babel-jest', {rootMode: "upward"}]}`
1571
+
See the [Code Transformation](CodeTransformation.md) section for more details and instructions on building your own transformer.
1576
1572
1577
1573
:::tip
1578
1574
1579
-
A transformer is only run once per file unless the file has changed. During the development of a transformer it can be useful to run Jest with `--no-cache` to frequently [delete Jest's cache](Troubleshooting.md#caching-issues).
1580
-
1581
-
When adding additional code transformers, this will overwrite the default config and `babel-jest` is no longer automatically loaded. If you want to use it to compile JavaScript or TypeScript, it has to be explicitly defined by adding `{"\\.[jt]sx?$": "babel-jest"}` to the transform property. See [babel-jest plugin](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup).
1575
+
Keep in mind that a transformer only runs once per file unless the file has changed.
1582
1576
1583
-
:::
1577
+
Remember to include the default `babel-jest` transformer explicitly, if you wish to use it alongside with additional code preprocessors:
1584
1578
1585
-
A transformer must be an object with at least a `process` function, and it's also recommended to include a `getCacheKey` function. If your transformer is written in ESM you should have a default export with that object.
1579
+
```json
1580
+
"transform": {
1581
+
"\\.[jt]sx?$": "babel-jest",
1582
+
"\\.css$": "some-css-transformer",
1583
+
}
1584
+
```
1586
1585
1587
-
If the tests are written using [native ESM](ECMAScriptModules.md) the transformer can export `processAsync` and `getCacheKeyAsync` instead or in addition to the synchronous variants.
Copy file name to clipboardExpand all lines: docs/Webpack.md
+13-12Lines changed: 13 additions & 12 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -83,16 +83,16 @@ Then all your className lookups on the styles object will be returned as-is (e.g
83
83
}
84
84
```
85
85
86
-
> Notice that Proxy is enabled in Node 6 by default. If you are not on Node 6 yet, make sure you invoke Jest using `node --harmony_proxies node_modules/.bin/jest`.
87
-
88
86
If `moduleNameMapper` cannot fulfill your requirements, you can use Jest's [`transform`](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object) config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that `require('logo.jpg');` returns `'logo'`) can be written as:
We've told Jest to ignore files matching a stylesheet or image extension, and instead, require our mock files. You can adjust the regular expression to match the file types your webpack config handles.
114
114
115
-
_Note: if you are using babel-jest with additional code preprocessors, you have to explicitly define babel-jest as a transformer for your JavaScript code to map `.js` files to the babel-jest module._
115
+
:::tip
116
+
117
+
Remember to include the default `babel-jest` transformer explicitly, if you wish to use it alongside with additional code preprocessors:
116
118
117
119
```json
118
120
"transform": {
119
-
"\\.js$": "babel-jest",
120
-
"\\.css$": "custom-transformer",
121
-
...
121
+
"\\.[jt]sx?$": "babel-jest",
122
+
"\\.css$": "some-css-transformer",
122
123
}
123
124
```
124
125
126
+
:::
127
+
125
128
### Configuring Jest to find our files
126
129
127
130
Now that Jest knows how to process our files, we need to tell it how to _find_ them. For webpack's `modulesDirectories`, and `extensions` options there are direct analogs in Jest's `moduleDirectories` and `moduleFileExtensions` options.
@@ -186,8 +189,7 @@ That's it! webpack is a complex and flexible tool, so you may have to make some
186
189
187
190
webpack 2 offers native support for ES modules. However, Jest runs in Node, and thus requires ES modules to be transpiled to CommonJS modules. As such, if you are using webpack 2, you most likely will want to configure Babel to transpile ES modules to CommonJS modules only in the `test` environment.
188
191
189
-
```json
190
-
// .babelrc
192
+
```json title=".babelrc"
191
193
{
192
194
"presets": [["env", {"modules": false}]],
193
195
@@ -203,8 +205,7 @@ webpack 2 offers native support for ES modules. However, Jest runs in Node, and
203
205
204
206
If you use dynamic imports (`import('some-file.js').then(module => ...)`), you need to enable the `dynamic-import-node` plugin.
0 commit comments