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.

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. 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. In addition, babel-jest will inject the Babel plugin necessary for mock hoisting talked about in ES Module mocking.

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: The API of a transformer is as follows:

  1. interface Transformer<OptionType = unknown> {
  2. /**
  3. * Indicates if the transformer is capabale of instrumenting the code for code coverage.
  4. *
  5. * If V8 coverage is _not_ active, and this is `true`, Jest will assume the code is instrumented.
  6. * If V8 coverage is _not_ active, and this is `false`. Jest will instrument the code returned by this transformer using Babel.
  7. */
  8. canInstrument?: boolean;
  9. createTransformer?: (options?: OptionType) => Transformer;
  10. getCacheKey?: (
  11. sourceText: string,
  12. sourcePath: string,
  13. options: TransformOptions<OptionType>,
  14. ) => string;
  15. process: (
  16. sourceText: string,
  17. sourcePath: string,
  18. options: TransformOptions<OptionType>,
  19. ) => TransformedSource;
  20. }
  21. interface TransformOptions<OptionType> {
  22. /**
  23. * If a transformer does module resolution and reads files, it should populate `cacheFS` so that
  24. * Jest avoids reading the same files again, improving performance. `cacheFS` stores entries of
  25. * <file path, file contents>
  26. */
  27. cacheFS: Map<string, string>;
  28. config: Config.ProjectConfig;
  29. /** A stringified version of the configuration - useful in cache busting */
  30. configString: string;
  31. instrument: boolean;
  32. // names are copied from babel: https://babeljs.io/docs/en/options#caller
  33. supportsDynamicImport: boolean;
  34. supportsExportNamespaceFrom: boolean;
  35. supportsStaticESM: boolean;
  36. supportsTopLevelAwait: boolean;
  37. /** the options passed through Jest's config by the user */
  38. transformerConfig: OptionType;
  39. }
  40. type TransformedSource =
  41. | {code: string; map?: RawSourceMap | string | null}
  42. | string;
  43. // 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)
  44. // 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 to help implement it. You can use @jest/create-cache-key-function to help implement it.

Note that ECMAScript module support is indicated by the passed in supports* options. Note that ECMAScript module 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 for details on the differences. 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 for details on the differences.

例子

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. If you want that you can use 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. One way of handling it in Jest is to replace the imported value with its filename.

  1. // fileTransformer.js
  2. const path = require('path');
  3. module.exports = {
  4. process(src, filename, config, options) {
  5. return 'module.exports = ' + JSON.stringify(path.basename(filename)) + ';';
  6. },
  7. };
  1. // jest.config.js
  2. module.exports = {
  3. transform: {
  4. '\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$':
  5. '<rootDir>/fileTransformer.js',
  6. },
  7. };