全局 API
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
在测试文件中,Jest 会将以下方法和对象注入全局环境。您无需通过 require 或 import 即可使用它们。但如果需要显式导入,可通过 import {describe, expect, test} from '@jest/globals' 实现。
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
本页中的 TypeScript 示例仅在显式导入 Jest API 的情况下才能按文档所述正常工作:
import {expect, jest, test} from '@jest/globals';
有关如何设置 Jest 与 TypeScript 配合使用的详细信息,请查阅入门指南。
方法
- 参数详解
afterAll(fn, timeout)afterEach(fn, timeout)beforeAll(fn, timeout)beforeEach(fn, timeout)describe(name, fn)describe.each(table)(name, fn, timeout)describe.only(name, fn)describe.only.each(table)(name, fn)describe.skip(name, fn)describe.skip.each(table)(name, fn)test(name, fn, timeout)test.concurrent(name, fn, timeout)test.concurrent.each(table)(name, fn, timeout)test.concurrent.only.each(table)(name, fn)test.concurrent.skip.each(table)(name, fn)test.each(table)(name, fn, timeout)test.failing(name, fn, timeout)test.failing.each(name, fn, timeout)test.only.failing(name, fn, timeout)test.skip.failing(name, fn, timeout)test.only(name, fn, timeout)test.only.each(table)(name, fn)test.skip(name, fn)test.skip.each(table)(name, fn)test.todo(name)
- TypeScript 用法
参数详解
afterAll(fn, timeout)
在当前文件所有测试完成后执行函数。若函数返回 Promise 或是生成器,Jest 会等待该 Promise 解析后再继续。
可选地,你可以提供 timeout 参数(单位:毫秒)来指定超时时间。默认超时为 5 秒。
适用于清理跨测试共享的全局状态。
例如:
const globalDatabase = makeGlobalDatabase();
function cleanUpDatabase(db) {
db.cleanUp();
}
afterAll(() => {
cleanUpDatabase(globalDatabase);
});
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});
test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});
此处的 afterAll 确保在所有测试 运行后调用 cleanUpDatabase。
若 afterAll 在 describe 块内,则会在该描述块末尾执行。
若需在每项测试后而非所有测试后清理,请改用 afterEach。
afterEach(fn, timeout)
在文件内每项测试完成后执行函数。若函数返回 Promise 或是生成器,Jest 会等待该 Promise 解析后再继续。
可选地,你可以提供 timeout 参数(单位:毫秒)来指定超时时间。默认超时为 5 秒。
适用于清理每项测试创建的临时状态。
例如:
const globalDatabase = makeGlobalDatabase();
function cleanUpDatabase(db) {
db.cleanUp();
}
afterEach(() => {
cleanUpDatabase(globalDatabase);
});
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});
test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});
此处的 afterEach 确保在每项测试运行后调用 cleanUpDatabase。
若 afterEach 在 describe 块内,则仅在该描述块内的测试完成后执行。
若需在所有测试完成后仅执行一次清理,请改用 afterAll。
beforeAll(fn, timeout)
在当前文件任何测试运行前执行函数。若函数返回 Promise 或是生成器,Jest 会等待该 Promise 解析后再运行测试。
可选地,你可以提供 timeout 参数(单位:毫秒)来指定超时时间。默认超时为 5 秒。
适用于设置多测试共享的全局状态。
例如:
const globalDatabase = makeGlobalDatabase();
beforeAll(() => {
// Clears the database and adds some testing data.
// Jest will wait for this promise to resolve before running tests.
return globalDatabase.clear().then(() => {
return globalDatabase.insert({testData: 'foo'});
});
});
// Since we only set up the database once in this example, it's important
// that our tests don't modify it.
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});
此处的 beforeAll 确保测试运行前完成数据库设置。若为同步设置可不使用 beforeAll。关键在于 Jest 会等待 Promise 解析,因此也支持异步设置。
若 beforeAll 在 describe 块内,则会在该描述块起始处执行。
若需在每项测试前而非所有测试前执行操作,请改用 beforeEach。
beforeEach(fn, timeout)
在文件内每项测试运行前执行函数。若函数返回 Promise 或是生成器,Jest 会等待该 Promise 解析后再运行测试。
可选地,你可以提供 timeout 参数(单位:毫秒)来指定超时时间。默认超时为 5 秒。
适用于重置多测试使用的全局状态。
例如:
const globalDatabase = makeGlobalDatabase();
beforeEach(() => {
// Clears the database and adds some testing data.
// Jest will wait for this promise to resolve before running tests.
return globalDatabase.clear().then(() => {
return globalDatabase.insert({testData: 'foo'});
});
});
test('can find things', () => {
return globalDatabase.find('thing', {}, results => {
expect(results.length).toBeGreaterThan(0);
});
});
test('can insert a thing', () => {
return globalDatabase.insert('thing', makeThing(), response => {
expect(response.success).toBeTruthy();
});
});
此处的 beforeEach 确保为每项测试重置数据库状态。
如果 beforeEach 位于 describe 代码块中,它会在该 describe 块内的每个测试运行前执行。
如果只需在任意测试运行前执行一次初始化代码,请改用 beforeAll。
describe(name, fn)
describe(name, fn) 创建分组块,将多个相关测试组合在一起。例如,若有一个预期美味但不酸的 myBeverage 对象,可这样测试:
const myBeverage = {
delicious: true,
sour: false,
};
describe('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});
test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});
这不是必须的——你可以直接在顶层编写 test 代码块。但若希望将测试分组组织,这种方式会很方便。
如果存在多层测试结构,也可以嵌套 describe 块:
const binaryStringToNumber = binString => {
if (!/^[01]+$/.test(binString)) {
throw new CustomError('Not a binary number.');
}
return parseInt(binString, 2);
};
describe('binaryStringToNumber', () => {
describe('given an invalid binary string', () => {
test('composed of non-numbers throws CustomError', () => {
expect(() => binaryStringToNumber('abc')).toThrow(CustomError);
});
test('with extra whitespace throws CustomError', () => {
expect(() => binaryStringToNumber(' 100')).toThrow(CustomError);
});
});
describe('given a valid binary string', () => {
test('returns the correct number', () => {
expect(binaryStringToNumber('100')).toBe(4);
});
});
});
describe.each(table)(name, fn, timeout)
当需要为不同数据重复编写相同测试套件时,可使用 describe.each。describe.each 允许编写一次测试套件并传入数据。
describe.each 提供两种 API:
1. describe.each(table)(name, fn, timeout)
-
table:一个Array,其元素为数组,包含传入fn的每行参数。如果传入一维基础类型数组,内部会自动转换为表格格式,例如[1, 2, 3] -> [[1], [2], [3]] -
name:String测试套件的标题- 使用
printf格式化 按位置注入参数生成唯一测试标题:%p- pretty-format%s- 字符串%d- 数字%i- 整数%f- 浮点数%j- JSON%o- 对象%#- 测试用例索引%$- 测试用例编号%%- 百分号(不消耗参数)
- 或通过
$variable注入测试用例对象的属性生成唯一标题:- 嵌套对象值可通过
$variable.path.to.value注入(仅支持自有属性,例如$variable.constructor.name无效) - 使用
$#注入测试用例索引 $variable不能与printf格式化混用(%%除外)
- 嵌套对象值可通过
- 使用
-
fn:Function要运行的测试套件函数,每行参数将作为该函数的参数传入 -
可选地,你可 以提供
timeout参数(单位:毫秒)来指定每行测试的超时时间。默认超时为 5 秒。
示例:
describe.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});
test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});
describe.each([
{a: 1, b: 1, expected: 2},
{a: 1, b: 2, expected: 3},
{a: 2, b: 1, expected: 3},
])('.add($a, $b)', ({a, b, expected}) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});
test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});
2. describe.each`table`(name, fn, timeout)
-
table:Tagged Template Literal- 首行用
|分隔变量名作为列标题 - 后续行使用
${value}语法提供数据
- 首行用
-
name:String测试套件的标题,使用$variable从标记模板表达式中注入测试数据到套件标题,并使用$#表示行索引。- 要注入嵌套对象值,可以提供键路径,例如
$variable.path.to.value(仅适用于“自有”属性,例如$variable.constructor.name将不起作用)
- 要注入嵌套对象值,可以提供键路径,例如
-
fn:Function类型, 表示要运行的测试套件函数,该函数将接收测试数据对象。 -
可选地,你可以提供
timeout参数(单位:毫秒)来指定每行测试的超时时间。默认超时为 5 秒。
示例:
describe.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('$a + $b', ({a, b, expected}) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected);
});
test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected);
});
});
describe.only(name, fn)
别名:fdescribe(name, fn)
当需要仅运行单个 describe 代码块时,可使用 describe.only:
describe.only('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});
test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});
describe('my other beverage', () => {
// ... will be skipped
});
describe.only.each(table)(name, fn)
别名:fdescribe.each(table)(name, fn) 和 fdescribe.each`table`(name, fn)
若需仅运行特定数据驱动测试套件,请使用 describe.only.each。
describe.only.each 支持两种调用方式:
describe.only.each(table)(name, fn)
describe.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected);
});
});
test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});
describe.only.each`table`(name, fn)
describe.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
test('passes', () => {
expect(a + b).toBe(expected);
});
});
test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});
describe.skip(name, fn)
别名:xdescribe(name, fn)
当需要跳过特定 describe 块内的测试时,可使用 describe.skip:
describe('my beverage', () => {
test('is delicious', () => {
expect(myBeverage.delicious).toBeTruthy();
});
test('is not sour', () => {
expect(myBeverage.sour).toBeFalsy();
});
});
describe.skip('my other beverage', () => {
// ... will be skipped
});
相比临时注释大段测试代码,使用 describe.skip 通常是更优雅的解决方案。注意 :describe 代码块本身仍会执行。如需跳过相关设置逻辑,请在 beforeAll 或 beforeEach 块中处理。
describe.skip.each(table)(name, fn)
别名:xdescribe.each(table)(name, fn) 和 xdescribe.each`table`(name, fn)
若需停止运行某个数据驱动测试套件,请使用 describe.skip.each。
describe.skip.each 支持两种调用方式:
describe.skip.each(table)(name, fn)
describe.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected); // will not be run
});
});
test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});
describe.skip.each`table`(name, fn)
describe.skip.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
test('will not be run', () => {
expect(a + b).toBe(expected); // will not be run
});
});
test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});
test(name, fn, timeout)
别名:it(name, fn, timeout)
测试文件的核心是 test 方法,用于执行单个测试用例。例如存在函数 inchesOfRain() 应返回零,完整测试可写作:
test('did not rain', () => {
expect(inchesOfRain()).toBe(0);
});
第一参数为测试名称;第二参数是包含断言逻辑的函数;第三参数(可选)timeout(毫秒单位)用于设置超时时间,默认 5 秒。
若 test 返回 Promise 对象,Jest 会等待其状态变更后才完成测试。例如 fetchBeverageList() 返回应包含 lemon 的列表时:
test('has lemon in it', () => {
return fetchBeverageList().then(list => {
expect(list).toContain('lemon');
});
});
即使 test 调用立即返回,测试需等待 promise 解析后才算完成。详见异步测试指南。
当测试函数接收参数(通常命名为 done)时,Jest 也会等待其回调。这在测试回调函数时特别有用。
test.concurrent(name, fn, timeout)
别名:it.concurrent(name, fn, timeout)
test.concurrent 目前处于实验阶段——有关功能缺失及其他问题详见此链接。
若需测试用例并行执行,请使用 test.concurrent。
第一个参数是测试名称;第二个参数是包含待测断言的异步函数。第三个参数(可选)是 timeout(单位:毫秒),用于指定超时时间。默认超时为 5 秒。
test.concurrent('addition of 2 numbers', async () => {
expect(5 + 3).toBe(8);
});
test.concurrent('subtraction 2 numbers', async () => {
expect(5 - 3).toBe(2);
});
使用 maxConcurrency 配置选项可限制 Jest 同时执行的最大测试数量。
test.concurrent.each(table)(name, fn, timeout)
别名:it.concurrent.each(table)(name, fn, timeout)
当需要重复执行相同逻辑但数据不同的测试时,使用 test.concurrent.each。test.each 允许编写一次测试并传入多组数据,所有测试将异步并发执行。
test.concurrent.each 支持两种调用方式:
1. test.concurrent.each(table)(name, fn, timeout)
-
table: 一个Array,其元素为数组,包含传递给测试fn的参数,每组参数对应一行。若传入基础类型的一维数组,内部会自动转换为二维数组(如[1, 2, 3] -> [[1], [2], [3]]) -
name:String测试块的标题- 通过
printf格式注入参数生成唯一测试标题:%p- pretty-format%s- 字符串%d- 数字%i- 整数%f- 浮点数%j- JSON%o- 对象%#- 测试用例索引%$- 测试用例编号%%- 百分号(不消耗参数)
- 通过
-
fn:Function类型,接收每行参数的测试函数(必须是异步函数) -
可选地,你可以提供
timeout参数(单位:毫秒)来指定每行测试的超时时间。默认超时为 5 秒。
示例:
test.concurrent.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected);
});
2. test.concurrent.each`table`(name, fn, timeout)
-
table:Tagged Template Literal- 首行用
|分隔变量名作为列标题 - 后续行使用
${value}语法提供数据
- 首行用
-
name:String测试标题,使用$variable将模板表达式数据注入标题- 嵌套对象使用键路径如
$variable.path.to.value(仅支持自有属性,例如$variable.constructor.name就不会生效)
- 嵌套对象使用键路径如
-
fn:Function类型,表示要运行的测试函数,该函数会接收测试数据对象(必须是异步函数) -
可选地,你可以提供
timeout参数(单位:毫秒)来指定每行测试的超时时间。默认超时为 5 秒。
示例:
test.concurrent.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected);
});
test.concurrent.only.each(table)(name, fn)
别名:it.concurrent.only.each(table)(name, fn)
当需要仅并发执行特定数据集测试时,使用 test.concurrent.only.each
test.concurrent.only.each 支持两种调用方式:
test.concurrent.only.each(table)(name, fn)
test.concurrent.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected);
});
test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});
test.only.each`table`(name, fn)
test.concurrent.only.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', async ({a, b, expected}) => {
expect(a + b).toBe(expected);
});
test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});
test.concurrent.skip.each(table)(name, fn)
别名:it.concurrent.skip.each(table)(name, fn)
当需要跳过一组异步数据驱动测试时,请使用 test.concurrent.skip.each。
test.concurrent.skip.each 支持两种调用方式: