Skip to content
开发文档
Usage
@swc/jest

@swc/jest

为了使 Jest 测试运行得更快,你可以使用 SWC 将默认的基于 JavaScript 的运行程序 (ts-jest) 替换为 直接 Rust 替代品 (opens in a new tab)

¥To make your Jest tests run faster, you can swap out the default JavaScript-based runner (ts-jest) for a drop-in Rust replacement (opens in a new tab) using SWC.

安装

¥Installation

pnpm i -D jest @swc/core @swc/jest

用法

¥Usage

jest.config.js 内,配置 Jest 以使用 SWC:

¥Inside jest.config.js, configure Jest to use SWC:

jest.config.js
module.exports = {
  transform: {
    '^.+\\.(t|j)sx?$': '@swc/jest',
  },
}

默认情况下,它将从 .swcrc 加载 SWC 配置。你还可以自定义它:

¥It will load the SWC configuration from .swcrc by default. You also can customize it:

jest.config.js
const fs = require('fs')
 
const config = JSON.parse(fs.readFileSync(`${__dirname}/.swcrc`, 'utf-8'))
 
module.exports = {
  transform: {
    '^.+\\.(t|j)sx?$': ['@swc/jest', { ...config, /* custom configuration in Jest */ }],
  },
}

Q & A

问:Jest 默认使用 CommonJS。但我想使用 ESM

¥Q: Jest uses CommonJS by default. But I want to use ESM

答:按照 指导 (opens in a new tab) 设置 Jest。

¥A: Setup Jest following this Guide (opens in a new tab).

对于 JavaScript,按如下方式编辑 package.json

¥For JavaScript, edit package.json as follows:

package.json
{
  // ...
  "type": "module"
}

对于 TypeScript,按如下方式编辑 jest.config.js

¥For TypeScript, edit jest.config.js as follows:

jest.config.js
module.exports = {
  // ...
  extensionsToTreatAsEsm: ['.ts', '.tsx'],
}

使用 --experimental-vm-modules 运行测试:

¥Run test with --experimental-vm-modules:

cross-env NODE_OPTIONS=--experimental-vm-modules jest
 
# or
node --experimental-vm-modules ./node_modules/jest/bin/jest.js

问:jsc.target 设置了什么 ECMAScript 目标?

¥Q: What ECMAScript target is set by jsc.target?

答:默认情况下,你的 Node 运行时支持的版本。

¥A: By default, the version supported by your Node runtime.

节点版本默认 jsc.target
12'es2018'
13'es2019'
14'es2020'
15'es2021'
16'es2021'
17'es2022'

你可以通过在 jest.config.js 中设置显式版本来自定义它:

¥You can customize this by setting an explicit version in jest.config.js:

jest.config.js
module.exports = {
    transform: {
        "^.+\\.(t|j)sx?$": [
            "@swc/jest",
            {
                jsc: {
                    target: "es2021",
                },
            },
        ],
    },
}
Last updated on November 24, 2023