Skip to main content
Version: 29.7

全局变量

在你的测试文件中,Jest 将每个方法和对象放入全局环境中。你无需要求或导入任何内容即可使用它们。但是,如果你更喜欢显式导入,则可以执行 import {describe, expect, test} from '@jest/globals'

¥In your test files, Jest puts each of these methods and objects into the global environment. You don't have to require or import anything to use them. However, if you prefer explicit imports, you can do import {describe, expect, test} from '@jest/globals'.

信息

仅当你显式导入 Jest API 时,此页面中的 TypeScript 示例才会按照文档说明的方式工作:

¥The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:

import {expect, jest, test} from '@jest/globals';

有关如何使用 TypeScript 设置 Jest 的详细信息,请参阅 入门 指南。

¥Consult the Getting Started guide for details on how to setup Jest with TypeScript.

方法

¥Methods


参考

¥Reference

afterAll(fn, timeout)

该文件中的所有测试完成后运行函数。如果函数返回一个 Promise 或者是一个生成器,Jest 会等待该 Promise 解析后再继续。

¥Runs a function after all the tests in this file have completed. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing.

或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待的时间。默认超时为 5 秒。

¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.

如果你想要清理跨测试共享的某些全局设置状态,这通常很有用。

¥This is often useful if you want to clean up some global setup state that is shared across tests.

例如:

¥For example:

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

¥Here the afterAll ensures that cleanUpDatabase is called after all tests run.

如果 afterAlldescribe 块内,则它在描述块的末尾运行。

¥If afterAll is inside a describe block, it runs at the end of the describe block.

如果你想在每次测试后而不是在所有测试后运行一些清理,请改用 afterEach

¥If you want to run some cleanup after every test instead of after all tests, use afterEach instead.

afterEach(fn, timeout)

此文件中的每一项测试完成后运行一个函数。如果函数返回一个 Promise 或者是一个生成器,Jest 会等待该 Promise 解析后再继续。

¥Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing.

或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待的时间。默认超时为 5 秒。

¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.

如果你想要清理每个测试创建的一些临时状态,这通常很有用。

¥This is often useful if you want to clean up some temporary state that is created by each test.

例如:

¥For example:

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

¥Here the afterEach ensures that cleanUpDatabase is called after each test runs.

如果 afterEach 位于 describe 块内,则它仅在该描述块内的测试之后运行。

¥If afterEach is inside a describe block, it only runs after the tests that are inside this describe block.

如果你只想在所有测试运行后运行一次清理操作,请改用 afterAll

¥If you want to run some cleanup just once, after all of the tests run, use afterAll instead.

beforeAll(fn, timeout)

在运行此文件中的任何测试之前运行一个函数。如果函数返回一个 Promise 或者是一个生成器,Jest 会在运行测试之前等待该 Promise 解析。

¥Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests.

或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待的时间。默认超时为 5 秒。

¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.

如果你想设置一些将由许多测试使用的全局状态,这通常很有用。

¥This is often useful if you want to set up some global state that will be used by many tests.

例如:

¥For example:

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 解决,因此你也可以进行异步设置。

¥Here the beforeAll ensures that the database is set up before tests run. If setup was synchronous, you could do this without beforeAll. The key is that Jest will wait for a promise to resolve, so you can have asynchronous setup as well.

如果 beforeAlldescribe 块内,则它在描述块的开头运行。

¥If beforeAll is inside a describe block, it runs at the beginning of the describe block.

如果你想在每个测试之前而不是任何测试运行之前运行某些内容,请改用 beforeEach

¥If you want to run something before every test instead of before any test runs, use beforeEach instead.

beforeEach(fn, timeout)

在运行此文件中的每个测试之前运行一个函数。如果函数返回一个 Promise 或者是一个生成器,Jest 会在运行测试之前等待该 Promise 解析。

¥Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test.

或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待的时间。默认超时为 5 秒。

¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.

如果你想重置许多测试将使用的某些全局状态,这通常很有用。

¥This is often useful if you want to reset some global state that will be used by many tests.

例如:

¥For example:

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 确保每次测试都会重置数据库。

¥Here the beforeEach ensures that the database is reset for each test.

如果 beforeEach 位于 describe 块内,则它针对描述块中的每个测试运行。

¥If beforeEach is inside a describe block, it runs for each test in the describe block.

如果你只需要在运行任何测试之前运行一些设置代码一次,请改用 beforeAll

¥If you only need to run some setup code once, before any tests run, use beforeAll instead.

describe(name, fn)

describe(name, fn) 创建一个将多个相关测试组合在一起的块。例如,如果你有一个 myBeverage 对象,该对象应该是美味但不酸的,你可以使用以下命令来测试它:

¥describe(name, fn) creates a block that groups together several related tests. For example, if you have a myBeverage object that is supposed to be delicious but not sour, you could test it with:

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 块。但如果你希望将测试组织成组,这会很方便。

¥This isn't required - you can write the test blocks directly at the top level. But this can be handy if you prefer your tests to be organized into groups.

如果你有测试层次结构,你还可以嵌套 describe 块:

¥You can also nest describe blocks if you have a hierarchy of tests:

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.eachdescribe.each 允许你编写一次测试套件并传入数据。

¥Use describe.each if you keep duplicating the same test suites with different data. describe.each allows you to write the test suite once and pass data in.

describe.each 有两个 API:

¥describe.each is available with two APIs:

1. describe.each(table)(name, fn, timeout)

  • table:数组的 Array 以及每行传递到 fn 中的参数。如果你传入一个一维基础类型数组,它将在内部映射到一个表,即 [1, 2, 3] -> [[1], [2], [3]]

    ¥table: Array of Arrays with the arguments that are passed into the fn for each row. If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. [1, 2, 3] -> [[1], [2], [3]].

  • nameString 测试套件的标题。

    ¥name: String the title of the test suite.

    • 通过使用 printf 格式 按位置注入参数来生成唯一的测试标题:

      ¥Generate unique test titles by positionally injecting parameters with printf formatting:

      • %p - pretty-format

      • %s-字符串。

        ¥%s- String.

      • %d-编号。

        ¥%d- Number.

      • %i - 整数。

        ¥%i - Integer.

      • %f - 浮点值。

        ¥%f - Floating point value.

      • %j - JSON。

      • %o - 目的。

        ¥%o - Object.

      • %# - 测试用例的索引。

        ¥%# - Index of the test case.

      • %% - 单个百分号 ('%')。这不会消耗参数。

        ¥%% - single percent sign ('%'). This does not consume an argument.

    • 或者通过使用 $variable 注入测试用例对象的属性来生成唯一的测试标题

      ¥Or generate unique test titles by injecting properties of test case object with $variable

      • 要注入嵌套对象值,你可以提供一个 keyPath,即 $variable.path.to.value

        ¥To inject nested object values use you can supply a keyPath i.e. $variable.path.to.value

      • 你可以使用 $# 注入测试用例的索引

        ¥You can use $# to inject the index of the test case

      • %% 之外,不能将 $variableprintf 格式一起使用

        ¥You cannot use $variable with the printf formatting except for %%

  • fnFunction 要运行的测试套件,这是将接收每行中的参数作为函数参数的函数。

    ¥fn: Function the suite of tests to be run, this is the function that will receive the parameters in each row as function arguments.

  • 或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待每行的时间。默认超时为 5 秒。

    ¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds.

示例:

¥Example:

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.eachtable(name, fn, timeout)

  • tableTagged Template Literal

    • 第一行变量名称列标题以 | 分隔

      ¥First row of variable name column headings separated with |

    • 使用 ${value} 语法作为模板字面量表达式提供的一行或多行后续数据。

      ¥One or more subsequent rows of data supplied as template literal expressions using ${value} syntax.

  • nameString 是测试套件的标题,使用 $variable 将测试数据从标记的模板表达式注入到套件标题中,$# 是行的索引。

    ¥name: String the title of the test suite, use $variable to inject test data into the suite title from the tagged template expressions, and $# for the index of the row.

    • 要注入嵌套对象值,你可以提供一个 keyPath,即 $variable.path.to.value

      ¥To inject nested object values use you can supply a keyPath i.e. $variable.path.to.value

  • fnFunction 要运行的测试套件,这是将接收测试数据对象的函数。

    ¥fn: Function the suite of tests to be run, this is the function that will receive the test data object.

  • 或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待每行的时间。默认超时为 5 秒。

    ¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds.

示例:

¥Example:

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)

¥Also under the alias: fdescribe(name, fn)

如果你只想运行一个描述块,则可以使用 describe.only

¥You can use describe.only if you want to run only one describe block:

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.eachtable(name, fn)

¥Also under the aliases: fdescribe.each(table)(name, fn) and fdescribe.each`table`(name, fn)

如果你只想运行数据驱动测试的特定测试套件,请使用 describe.only.each

¥Use describe.only.each if you want to only run specific tests suites of data driven tests.

describe.only.each 有两个 API:

¥describe.only.each is available with two APIs:

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.eachtable(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)

¥Also under the alias: xdescribe(name, fn)

如果你不想运行特定 describe 块的测试,可以使用 describe.skip

¥You can use describe.skip if you do not want to run the tests of a particular describe block:

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 块仍将运行。如果你有一些设置也应该跳过,请在 beforeAllbeforeEach 块中进行。

¥Using describe.skip is often a cleaner alternative to temporarily commenting out a chunk of tests. Beware that the describe block will still run. If you have some setup that also should be skipped, do it in a beforeAll or beforeEach block.

describe.skip.each(table)(name, fn)

也在别名下:xdescribe.each(table)(name, fn)xdescribe.eachtable(name, fn)

¥Also under the aliases: xdescribe.each(table)(name, fn) and xdescribe.each`table`(name, fn)

如果你想停止运行一套数据驱动测试,请使用 describe.skip.each

¥Use describe.skip.each if you want to stop running a suite of data driven tests.

describe.skip.each 有两个 API:

¥describe.skip.each is available with two APIs:

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.eachtable(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)

¥Also under the alias: it(name, fn, timeout)

测试文件中你所需要的只是运行测试的 test 方法。例如,假设有一个函数 inchesOfRain() 应为零。你的整个测试可能是:

¥All you need in a test file is the test method which runs a test. For example, let's say there's a function inchesOfRain() that should be zero. Your whole test could be:

test('did not rain', () => {
expect(inchesOfRain()).toBe(0);
});

第一个参数是测试名称;第二个参数是一个包含要测试的期望的函数。第三个参数(可选)是 timeout(以毫秒为单位),用于指定中止之前等待的时间。默认超时为 5 秒。

¥The first argument is the test name; the second argument is a function that contains the expectations to test. The third argument (optional) is timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.

如果从 test 返回 Promise,Jest 将等待 Promise 解析后再让测试完成。例如,假设 fetchBeverageList() 返回一个 promise,该 promise 应该解析为其中包含 lemon 的列表。你可以使用以下方法进行测试:

¥If a promise is returned from test, Jest will wait for the promise to resolve before letting the test complete. For example, let's say fetchBeverageList() returns a promise that is supposed to resolve to a list that has lemon in it. You can test this with:

test('has lemon in it', () => {
return fetchBeverageList().then(list => {
expect(list).toContain('lemon');
});
});

尽管对 test 的调用将立即返回,但在 promise 解决之前测试不会完成。欲了解更多详情,请参阅 测试异步代码 页。

¥Even though the call to test will return right away, the test doesn't complete until the promise resolves. For more details, see Testing Asynchronous Code page.

提示

如果你向测试函数(通常称为 done)提供参数,Jest 也会等待。当你想要测试 callbacks 时,这可能会很方便。

¥Jest will also wait if you provide an argument to the test function, usually called done. This could be handy when you want to test callbacks.

test.concurrent(name, fn, timeout)

也在别名下:it.concurrent(name, fn, timeout)

¥Also under the alias: it.concurrent(name, fn, timeout)

提醒

test.concurrent 被认为是实验性的 - 有关缺失功能和其他问题的详细信息,请参阅 此处

¥test.concurrent is considered experimental - see here for details on missing features and other issues.

如果你希望测试同时运行,请使用 test.concurrent

¥Use test.concurrent if you want the test to run concurrently.

第一个参数是测试名称;第二个参数是一个异步函数,其中包含要测试的期望。第三个参数(可选)是 timeout(以毫秒为单位),用于指定中止之前等待的时间。默认超时为 5 秒。

¥The first argument is the test name; the second argument is an asynchronous function that contains the expectations to test. The third argument (optional) is timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.

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 同时执行超过指定数量的测试。

¥Use the maxConcurrency configuration option to prevent Jest from executing more than the specified amount of tests at the same time.

test.concurrent.each(table)(name, fn, timeout)

也在别名下:it.concurrent.each(table)(name, fn, timeout)

¥Also under the alias: it.concurrent.each(table)(name, fn, timeout)

如果你不断使用不同的数据重复相同的测试,请使用 test.concurrent.eachtest.each 允许你编写一次测试并传入数据,测试全部异步运行。

¥Use test.concurrent.each if you keep duplicating the same test with different data. test.each allows you to write the test once and pass data in, the tests are all run asynchronously.

test.concurrent.each 有两个 API:

¥test.concurrent.each is available with two APIs:

1. test.concurrent.each(table)(name, fn, timeout)

  • table:数组的 Array 以及传递到每行测试 fn 中的参数。如果你传入一个一维基础类型数组,它将在内部映射到一个表,即 [1, 2, 3] -> [[1], [2], [3]]

    ¥table: Array of Arrays with the arguments that are passed into the test fn for each row. If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. [1, 2, 3] -> [[1], [2], [3]]

  • nameString 测试块的标题。

    ¥name: String the title of the test block.

    • 通过使用 printf 格式 按位置注入参数来生成唯一的测试标题:

      ¥Generate unique test titles by positionally injecting parameters with printf formatting:

      • %p - pretty-format

      • %s-字符串。

        ¥%s- String.

      • %d-编号。

        ¥%d- Number.

      • %i - 整数。

        ¥%i - Integer.

      • %f - 浮点值。

        ¥%f - Floating point value.

      • %j - JSON。

      • %o - 目的。

        ¥%o - Object.

      • %# - 测试用例的索引。

        ¥%# - Index of the test case.

      • %% - 单个百分号 ('%')。这不会消耗参数。

        ¥%% - single percent sign ('%'). This does not consume an argument.

  • fnFunction 要运行的测试,这是将接收每行中的参数作为函数参数的函数,这必须是异步函数。

    ¥fn: Function the test to be run, this is the function that will receive the parameters in each row as function arguments, this will have to be an asynchronous function.

  • 或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待每行的时间。默认超时为 5 秒。

    ¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds.

示例:

¥Example:

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.eachtable(name, fn, timeout)

  • tableTagged Template Literal

    • 第一行变量名称列标题以 | 分隔

      ¥First row of variable name column headings separated with |

    • 使用 ${value} 语法作为模板字面量表达式提供的一行或多行后续数据。

      ¥One or more subsequent rows of data supplied as template literal expressions using ${value} syntax.

  • nameString 测试的标题,使用 $variable 将测试数据从标记的模板表达式注入到测试标题中。

    ¥name: String the title of the test, use $variable to inject test data into the test title from the tagged template expressions.

    • 要注入嵌套对象值,你可以提供一个 keyPath,即 $variable.path.to.value

      ¥To inject nested object values use you can supply a keyPath i.e. $variable.path.to.value

  • fnFunction 要运行的测试,这是将接收测试数据对象的函数,这必须是异步函数。

    ¥fn: Function the test to be run, this is the function that will receive the test data object, this will have to be an asynchronous function.

  • 或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待每行的时间。默认超时为 5 秒。

    ¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds.

示例:

¥Example:

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)

¥Also under the alias: it.concurrent.only.each(table)(name, fn)

如果你只想同时运行具有不同测试数据的特定测试,请使用 test.concurrent.only.each

¥Use test.concurrent.only.each if you want to only run specific tests with different test data concurrently.

test.concurrent.only.each 有两个 API:

¥test.concurrent.only.each is available with two APIs:

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.eachtable(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)

¥Also under the alias: it.concurrent.skip.each(table)(name, fn)

如果你想停止运行异步数据驱动测试的集合,请使用 test.concurrent.skip.each

¥Use test.concurrent.skip.each if you want to stop running a collection of asynchronous data driven tests.

test.concurrent.skip.each 有两个 API:

¥test.concurrent.skip.each is available with two APIs:

test.concurrent.skip.each(table)(name, fn)

test.concurrent.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', async (a, b, expected) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.concurrent.skip.eachtable(name, fn)

test.concurrent.skip.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); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.each(table)(name, fn, timeout)

也在别名下:it.each(table)(name, fn)it.eachtable(name, fn)

¥Also under the alias: it.each(table)(name, fn) and it.each`table`(name, fn)

如果你不断使用不同的数据重复相同的测试,请使用 test.eachtest.each 允许你编写一次测试并传入数据。

¥Use test.each if you keep duplicating the same test with different data. test.each allows you to write the test once and pass data in.

test.each 有两个 API:

¥test.each is available with two APIs:

1. test.each(table)(name, fn, timeout)

  • table:数组的 Array 以及传递到每行测试 fn 中的参数。如果你传入一个一维基础类型数组,它将在内部映射到一个表,即 [1, 2, 3] -> [[1], [2], [3]]

    ¥table: Array of Arrays with the arguments that are passed into the test fn for each row. If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. [1, 2, 3] -> [[1], [2], [3]]

  • nameString 测试块的标题。

    ¥name: String the title of the test block.

    • 通过使用 printf 格式 按位置注入参数来生成唯一的测试标题:

      ¥Generate unique test titles by positionally injecting parameters with printf formatting:

      • %p - pretty-format

      • %s-字符串。

        ¥%s- String.

      • %d-编号。

        ¥%d- Number.

      • %i - 整数。

        ¥%i - Integer.

      • %f - 浮点值。

        ¥%f - Floating point value.

      • %j - JSON。

      • %o - 目的。

        ¥%o - Object.

      • %# - 测试用例的索引。

        ¥%# - Index of the test case.

      • %% - 单个百分号 ('%')。这不会消耗参数。

        ¥%% - single percent sign ('%'). This does not consume an argument.

    • 或者通过使用 $variable 注入测试用例对象的属性来生成唯一的测试标题

      ¥Or generate unique test titles by injecting properties of test case object with $variable

      • 要注入嵌套对象值,你可以提供一个 keyPath,即 $variable.path.to.value

        ¥To inject nested object values use you can supply a keyPath i.e. $variable.path.to.value

      • 你可以使用 $# 注入测试用例的索引

        ¥You can use $# to inject the index of the test case

      • %% 之外,不能将 $variableprintf 格式一起使用

        ¥You cannot use $variable with the printf formatting except for %%

  • fnFunction 要运行的测试,这是将接收每行中的参数作为函数参数的函数。

    ¥fn: Function the test to be run, this is the function that will receive the parameters in each row as function arguments.

  • 或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待每行的时间。默认超时为 5 秒。

    ¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds.

示例:

¥Example:

test.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected);
});
test.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}) => {
expect(a + b).toBe(expected);
});

2. test.eachtable(name, fn, timeout)

  • tableTagged Template Literal

    • 第一行变量名称列标题以 | 分隔

      ¥First row of variable name column headings separated with |

    • 使用 ${value} 语法作为模板字面量表达式提供的一行或多行后续数据。

      ¥One or more subsequent rows of data supplied as template literal expressions using ${value} syntax.

  • nameString 测试的标题,使用 $variable 将测试数据从标记的模板表达式注入到测试标题中。

    ¥name: String the title of the test, use $variable to inject test data into the test title from the tagged template expressions.

    • 要注入嵌套对象值,你可以提供一个 keyPath,即 $variable.path.to.value

      ¥To inject nested object values use you can supply a keyPath i.e. $variable.path.to.value

  • fnFunction 要运行的测试,这是将接收测试数据对象的函数。

    ¥fn: Function the test to be run, this is the function that will receive the test data object.

  • 或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待每行的时间。默认超时为 5 秒。

    ¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds.

示例:

¥Example:

test.each`
a | b | expected
${1} | ${1} | ${2}
${1} | ${2} | ${3}
${2} | ${1} | ${3}
`('returns $expected when $a is added to $b', ({a, b, expected}) => {
expect(a + b).toBe(expected);
});

test.failing(name, fn, timeout)

也在别名下:it.failing(name, fn, timeout)

¥Also under the alias: it.failing(name, fn, timeout)

注意

这仅适用于默认的 jest-circus 运行器。

¥This is only available with the default jest-circus runner.

当你编写测试并预计它会失败时,请使用 test.failing。这些测试的行为方式与正常测试的行为方式不同。如果 failing 测试抛出任何错误,那么它将通过。如果不抛出就会失败。

¥Use test.failing when you are writing a test and expecting it to fail. These tests will behave the other way normal tests do. If failing test will throw any errors then it will pass. If it does not throw it will fail.

提示

你可以使用这种类型的测试,即以 BDD 方式编写代码时。在这种情况下,测试在通过之前不会显示为失败。然后你只需删除 failing 修饰符即可让它们通过。

¥You can use this type of test i.e. when writing code in a BDD way. In that case the tests will not show up as failing until they pass. Then you can just remove the failing modifier to make them pass.

即使你不知道如何修复错误,它也可能是向项目贡献失败测试的好方法。

¥It can also be a nice way to contribute failing tests to a project, even if you don't know how to fix the bug.

示例:

¥Example:

test.failing('it is not equal', () => {
expect(5).toBe(6); // this test will pass
});

test.failing('it is equal', () => {
expect(10).toBe(10); // this test will fail
});

test.failing.each(name, fn, timeout)

也在别名下:it.failing.each(table)(name, fn)it.failing.eachtable(name, fn)

¥Also under the alias: it.failing.each(table)(name, fn) and it.failing.each`table`(name, fn)

注意

这仅适用于默认的 jest-circus 运行器。

¥This is only available with the default jest-circus runner.

你还可以通过在 failing 之后添加 each 来一次运行多个测试。

¥You can also run multiple tests at once by adding each after failing.

示例:

¥Example:

test.failing.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}) => {
expect(a + b).toBe(expected);
});

test.only.failing(name, fn, timeout)

也在别名下:it.only.failing(name, fn, timeout)fit.failing(name, fn, timeout)

¥Also under the aliases: it.only.failing(name, fn, timeout), fit.failing(name, fn, timeout)

注意

这仅适用于默认的 jest-circus 运行器。

¥This is only available with the default jest-circus runner.

如果你只想运行特定的失败测试,请使用 test.only.failing

¥Use test.only.failing if you want to only run a specific failing test.

test.skip.failing(name, fn, timeout)

也在别名下:it.skip.failing(name, fn, timeout)xit.failing(name, fn, timeout)xtest.failing(name, fn, timeout)

¥Also under the aliases: it.skip.failing(name, fn, timeout), xit.failing(name, fn, timeout), xtest.failing(name, fn, timeout)

注意

这仅适用于默认的 jest-circus 运行器。

¥This is only available with the default jest-circus runner.

如果你想跳过运行特定的失败测试,请使用 test.skip.failing

¥Use test.skip.failing if you want to skip running a specific failing test.

test.only(name, fn, timeout)

也在别名下:it.only(name, fn, timeout)fit(name, fn, timeout)

¥Also under the aliases: it.only(name, fn, timeout), and fit(name, fn, timeout)

当你调试大型测试文件时,你通常只想运行测试的子集。你可以使用 .only 指定你只想在该测试文件中运行哪些测试。

¥When you are debugging a large test file, you will often only want to run a subset of tests. You can use .only to specify which tests are the only ones you want to run in that test file.

或者,你可以提供 timeout(以毫秒为单位)来指定中止之前等待的时间。默认超时为 5 秒。

¥Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.

例如,假设你进行了以下测试:

¥For example, let's say you had these tests:

test.only('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});

test('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});

只有 "正在下雨" 测试将在该测试文件中运行,因为它是与 test.only 一起运行的。

¥Only the "it is raining" test will run in that test file, since it is run with test.only.

通常你不会使用 test.only 将代码检查到源代码管理中 - 你可以使用它进行调试,并在修复了损坏的测试后将其删除。

¥Usually you wouldn't check code using test.only into source control - you would use it for debugging, and remove it once you have fixed the broken tests.

test.only.each(table)(name, fn)

也在别名下:it.only.each(table)(name, fn)fit.each(table)(name, fn)it.only.eachtable(name, fn)fit.eachtable(name, fn)

¥Also under the aliases: it.only.each(table)(name, fn), fit.each(table)(name, fn), it.only.each`table`(name, fn) and fit.each`table`(name, fn)

如果你只想使用不同的测试数据运行特定测试,请使用 test.only.each

¥Use test.only.each if you want to only run specific tests with different test data.

test.only.each 有两个 API:

¥test.only.each is available with two APIs:

test.only.each(table)(name, fn)

test.only.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected);
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.only.eachtable(name, fn)

test.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}) => {
expect(a + b).toBe(expected);
});

test('will not be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.skip(name, fn)

也在别名下:it.skip(name, fn)xit(name, fn)xtest(name, fn)

¥Also under the aliases: it.skip(name, fn), xit(name, fn), and xtest(name, fn)

当你维护大型代码库时,有时可能会发现某个测试由于某种原因暂时中断。如果你想跳过运行此测试,但又不想删除此代码,可以使用 test.skip 指定要跳过的某些测试。

¥When you are maintaining a large codebase, you may sometimes find a test that is temporarily broken for some reason. If you want to skip running this test, but you don't want to delete this code, you can use test.skip to specify some tests to skip.

例如,假设你进行了以下测试:

¥For example, let's say you had these tests:

test('it is raining', () => {
expect(inchesOfRain()).toBeGreaterThan(0);
});

test.skip('it is not snowing', () => {
expect(inchesOfSnow()).toBe(0);
});

只有 "正在下雨" 测试将运行,因为其他测试是使用 test.skip 运行的。

¥Only the "it is raining" test will run, since the other test is run with test.skip.

你可以注释掉该测试,但使用 test.skip 通常会更好一些,因为它将保持缩进和语法高亮。

¥You could comment the test out, but it's often a bit nicer to use test.skip because it will maintain indentation and syntax highlighting.

test.skip.each(table)(name, fn)

也在别名下:it.skip.each(table)(name, fn)xit.each(table)(name, fn)xtest.each(table)(name, fn)it.skip.eachtable(name, fn)xit.eachtable(name, fn)xtest.eachtable(name, fn)

¥Also under the aliases: it.skip.each(table)(name, fn), xit.each(table)(name, fn), xtest.each(table)(name, fn), it.skip.each`table`(name, fn), xit.each`table`(name, fn) and xtest.each`table`(name, fn)

如果你想停止运行数据驱动测试的集合,请使用 test.skip.each

¥Use test.skip.each if you want to stop running a collection of data driven tests.

test.skip.each 有两个 API:

¥test.skip.each is available with two APIs:

test.skip.each(table)(name, fn)

test.skip.each([
[1, 1, 2],
[1, 2, 3],
[2, 1, 3],
])('.add(%i, %i)', (a, b, expected) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.skip.eachtable(name, fn)

test.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}) => {
expect(a + b).toBe(expected); // will not be run
});

test('will be run', () => {
expect(1 / 0).toBe(Infinity);
});

test.todo(name)

也在别名下:it.todo(name)

¥Also under the alias: it.todo(name)

当你计划编写测试时,请使用 test.todo。这些测试将在最后的摘要输出中高亮,以便你知道还需要执行多少测试。

¥Use test.todo when you are planning on writing tests. These tests will be highlighted in the summary output at the end so you know how many tests you still need todo.

const add = (a, b) => a + b;

test.todo('add should be associative');
提示

如果你向 test.todo 传递测试回调函数,它会抛出错误。如果你已经实现了测试,但不希望它运行,请改用 test.skip

¥test.todo will throw an error if you pass it a test callback function. Use test.skip instead, if you already implemented the test, but do not want it to run.

TypeScript 用法

¥TypeScript Usage

信息

仅当你显式导入 Jest API 时,此页面中的 TypeScript 示例才会按照文档说明的方式工作:

¥The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:

import {expect, jest, test} from '@jest/globals';

有关如何使用 TypeScript 设置 Jest 的详细信息,请参阅 入门 指南。

¥Consult the Getting Started guide for details on how to setup Jest with TypeScript.

.each

.each 修饰符提供了几种不同的方法来定义测试用例表。某些 API 具有与传递给 describetest 回调函数的参数类型推断相关的警告。让我们逐一看一下。

¥The .each modifier offers few different ways to define a table of the test cases. Some of the APIs have caveats related with the type inference of the arguments which are passed to describe or test callback functions. Let's take a look at each of them.

注意

为简单起见,选择 test.each 作为示例,但在可以使用 .each 修饰符的所有情况下,类型推断都是相同的:describe.eachtest.concurrent.only.eachtest.skip.each

¥For simplicity test.each is picked for the examples, but the type inference is identical in all cases where .each modifier can be used: describe.each, test.concurrent.only.each, test.skip.each, etc.

对象数组

¥Array of objects

对象数组 API 最冗长,但它使类型推断成为一项轻松的任务。可以内联 table

¥The array of objects API is most verbose, but it makes the type inference a painless task. A table can be inlined:

import {test} from '@jest/globals';

test.each([
{name: 'a', path: 'path/to/a', count: 1, write: true},
{name: 'b', path: 'path/to/b', count: 3},
])('inline table', ({name, path, count, write}) => {
// arguments are typed as expected, e.g. `write: boolean | undefined`
});

或者单独声明为变量:

¥Or declared separately as a variable:

import {test} from '@jest/globals';

const table = [
{a: 1, b: 2, expected: 'three', extra: true},
{a: 3, b: 4, expected: 'seven', extra: false},
{a: 5, b: 6, expected: 'eleven'},
];

test.each(table)('table as a variable', ({a, b, expected, extra}) => {
// again everything is typed as expected, e.g. `extra: boolean | undefined`
});

数组的数组

¥Array of arrays

数组的数组样式可以与内联表顺利配合:

¥The array of arrays style will work smoothly with inlined tables:

import {test} from '@jest/globals';

test.each([
[1, 2, 'three', true],
[3, 4, 'seven', false],
[5, 6, 'eleven'],
])('inline table example', (a, b, expected, extra) => {
// arguments are typed as expected, e.g. `extra: boolean | undefined`
});

但是,如果将表声明为单独的变量,则必须将其类型化为元组数组以进行正确的类型推断(仅当行中的所有元素都具有相同类型时才不需要这样做):

¥However, if a table is declared as a separate variable, it must be typed as an array of tuples for correct type inference (this is not needed only if all elements of a row are of the same type):

import {test} from '@jest/globals';

const table: Array<[number, number, string, boolean?]> = [
[1, 2, 'three', true],
[3, 4, 'seven', false],
[5, 6, 'eleven'],
];

test.each(table)('table as a variable example', (a, b, expected, extra) => {
// without the annotation types are incorrect, e.g. `a: number | string | boolean`
});

模板字面量

¥Template literal

如果所有值都具有相同类型,则模板字面量 API 将正确键入参数:

¥If all values are of the same type, the template literal API will type the arguments correctly:

import {test} from '@jest/globals';

test.each`
a | b | expected
${1} | ${2} | ${3}
${3} | ${4} | ${7}
${5} | ${6} | ${11}
`('template literal example', ({a, b, expected}) => {
// all arguments are of type `number`
});

否则它将需要一个泛型类型参数:

¥Otherwise it will require a generic type argument:

import {test} from '@jest/globals';

test.each<{a: number; b: number; expected: string; extra?: boolean}>`
a | b | expected | extra
${1} | ${2} | ${'three'} | ${true}
${3} | ${4} | ${'seven'} | ${false}
${5} | ${6} | ${'eleven'}
`('template literal example', ({a, b, expected, extra}) => {
// without the generic argument in this case types would default to `unknown`
});