-
-
Notifications
You must be signed in to change notification settings - Fork 6.6k
chore(jest-transform): refactor transformer API to reduce number of arguments #10834
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
3af551e
chore(docs): update babel transformer example
SimenB 3ef146b
chore(jest-transform): refactor transformer API to reduce number of a…
SimenB 0f3b59d
mention esm for transformers
SimenB e2f0881
instrument docs
SimenB 26e213f
cache key docs
SimenB 9da4881
typo
SimenB 57912eb
prettier
SimenB cc52a5b
tests
SimenB babb77b
chore: update jest-create-cache-key-function
SimenB afca168
patch fbjs-scripts
SimenB a9d9cbf
tweak cache creater function
SimenB e747197
generic
SimenB 13ce59d
less syntax
SimenB c5c31e5
link to new docs from syntax error
SimenB df257c5
make @jest/create-cache-key-function more type safe
SimenB 1c0294c
Update packages/jest-transform/src/enhanceUnexpectedTokenMessage.ts
SimenB File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
--- | ||
id: code-transformation | ||
title: Code Transformation | ||
--- | ||
|
||
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. | ||
|
||
Jest supports this via the [`transform` configuration option](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object). | ||
|
||
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. | ||
|
||
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 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). | ||
|
||
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. | ||
|
||
## Writing custom transformers | ||
|
||
You can write you own transformer. The API of a transformer is as follows: | ||
|
||
```ts | ||
interface Transformer<OptionType = unknown> { | ||
/** | ||
* Indicates if the transformer is capabale of instrumenting the code for code coverage. | ||
* | ||
* If V8 coverage is _not_ active, and this is `true`, Jest will assume the code is instrumented. | ||
* If V8 coverage is _not_ active, and this is `false`. Jest will instrument the code returned by this transformer using Babel. | ||
*/ | ||
canInstrument?: boolean; | ||
createTransformer?: (options?: OptionType) => Transformer; | ||
|
||
getCacheKey?: ( | ||
sourceText: string, | ||
sourcePath: string, | ||
options: TransformOptions, | ||
) => string; | ||
|
||
process: ( | ||
sourceText: string, | ||
sourcePath: string, | ||
options: TransformOptions, | ||
) => TransformedSource; | ||
} | ||
|
||
interface TransformOptions { | ||
config: Config.ProjectConfig; | ||
/** A stringified version of the configuration - useful in cache busting */ | ||
configString: string; | ||
instrument: boolean; | ||
// names are copied from babel: https://babeljs.io/docs/en/options#caller | ||
supportsDynamicImport: boolean; | ||
supportsExportNamespaceFrom: boolean; | ||
supportsStaticESM: boolean; | ||
supportsTopLevelAwait: boolean; | ||
} | ||
|
||
type TransformedSource = | ||
| {code: string; map?: RawSourceMap | string | null} | ||
| string; | ||
|
||
// Config.ProjectConfig can be seen in in code [here](https://github.com/facebook/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L323) | ||
// RawSourceMap comes from [`source-map`](https://github.com/mozilla/source-map/blob/0.6.1/source-map.d.ts#L6-L12) | ||
``` | ||
|
||
As can be seen, only `process` is mandatory to implement, although we highly recommend implementing `getCacheKey` as well, so we don't waste resources transpiling the same source file when we can read its previous result from disk. You can use [`@jest/create-cache-key-function`](https://www.npmjs.com/package/@jest/create-cache-key-function) to help implement it. | ||
|
||
Note that [ECMAScript module](ECMAScriptModules.md) support is indicated by the passed in `supports*` options. Specifically `supportsDynamicImport: true` means the transformer can return `import()` expressions, which is supported by both ESM and CJS. If `supportsStaticESM: true` it means top level `import` statements are supported and the code will be interpreted as ESM and not CJS. See [Node's docs](https://nodejs.org/api/esm.html#esm_differences_between_es_modules_and_commonjs) for details on the differences. | ||
|
||
### Examples | ||
|
||
### TypeScript with type checking | ||
|
||
While `babel-jest` by default will transpile TypeScript files, Babel will not verify the types. If you want that you can use [`ts-jest`](https://github.com/kulshekhar/ts-jest). | ||
|
||
#### Transforming images to their path | ||
|
||
Importing images is a way to include them in your browser bundle, but they are not valid JavaScript. One way of handling it in Jest is to replace the imported value with its filename. | ||
|
||
```js | ||
// fileTransformer.js | ||
const path = require('path'); | ||
|
||
module.exports = { | ||
process(src, filename, config, options) { | ||
return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';'; | ||
}, | ||
}; | ||
``` | ||
|
||
```js | ||
// jest.config.js | ||
|
||
module.exports = { | ||
transform: { | ||
'\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$': | ||
'<rootDir>/fileTransformer.js', | ||
}, | ||
}; | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -144,6 +144,7 @@ | |
}, | ||
"resolutions": { | ||
"@types/jest/jest-diff": "^25.1.0", | ||
"@types/jest/pretty-format": "^25.1.0" | ||
"@types/jest/pretty-format": "^25.1.0", | ||
"fbjs-scripts": "patch:fbjs-scripts@^1.1.0#./patches/fbjs-scripts.patch" | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.