全局设定
Jest会将这些方法和对象注入到测试文件的全局环境里, 所以你在使用的时候不再需要进行require或者import。 However, if you prefer explicit imports, you can do import {describe, expect, test} from '@jest/globals'.
The TypeScript examples from this page will only work as documented if you explicitly import Jest APIs:
import {expect, jest, test} from '@jest/globals';
Consult the Getting Started guide for details on how to setup Jest with 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 Usage
参考
afterAll(fn, timeout)
文件内所有测试完成后执行的钩子函数。 如果传入的回调函数返回值是 promise 或者 generator,Jest 会等待 promise resolve 再继续执行。
Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.
使用 afterAll 非常方便你清理一些在测试用例之间共享的全局状态。
例如:
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();
});
});
Here the afterAll ensures that cleanUpDatabase is called after all tests run.
If afterAll is inside a describe block, it runs at the end of the describe block.
If you want to run some cleanup after every test instead of after all tests, use afterEach instead.
afterEach(fn, timeout)
文件内每个测试完成后执行的钩子函数。 如果传入的回调函数返回值是 promise 或者 generator,Jest 会等待 promise resolve 再继续执行。
Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.
使用 afterEach 会非常方便你清理一些在每个测试中创建的临时状态。
例如:
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();
});
});
Here the afterEach ensures that cleanUpDatabase is called after each test runs.
If afterEach is inside a describe block, it only runs after the tests that are inside this describe block.
If you want to run some cleanup just once, after all of the tests run, use afterAll instead.
beforeAll(fn, timeout)
文件内所有测试开始前执行的钩子函数。 如果传入的回调函数返回值是 promise 或者 generator,Jest 会等待 promise resolve 再继续执行。
Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.
使用 beforeAll 会非常方便你设置一些在测试用例之间共享的全局状态。
例如:
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);
});
});
Here the beforeAll ensures that the database is set up before tests run. If setup was synchronous, you could do this without beforeAll. 关键是 Jest 会等待 promise resolve,所以可以进行异步的初始化操作。
If beforeAll is inside a describe block, it runs at the beginning of the describe block.
If you want to run something before every test instead of before any test runs, use beforeEach instead.
beforeEach(fn, timeout)
文件内每个测试开始前执行的钩子函数。 如果传入的回调函数返回值是 promise 或者 generator,Jest 会等待 promise resolve 再继续执行测试。
Optionally, you can provide a timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.
使用 beforeEach 非常方便你重新设置一些全局状态在每个测试开始前。
例如:
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();
});
});
Here the beforeEach ensures that the database is reset for each test.
If beforeEach is inside a describe block, it runs for each test in the describe block.
If you only need to run some setup code once, before any tests run, use beforeAll instead.
describe(name, fn)
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();
});
});
This isn't required - you can write the test blocks directly at the top level. 但是如果你习惯按组编写测试,使用 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)
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 is available with two APIs:
1. describe.each(table)(name, fn, timeout)
-
table:Arrayof Arrays with the arguments that are passed into thefnfor 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]]. -
name:Stringthe title of the test suite.- Generate unique test titles by positionally injecting parameters with
printfformatting:%p- pretty-format.%s- String.%d- Number.%i- Integer.%f- Floating point value.%j- JSON.%o- Object.%#- Index of the test case.%$- Number of the test case.%%- single percent sign ('%'). 它不使用参数。
- Or generate unique test titles by injecting properties of test case object with
$variable- To inject nested object values use you can supply a keyPath i.e.
$variable.path.to.value(only works for "own" properties, e.g.$variable.constructor.namewouldn't work) - You can use
$#to inject the index of the test case - You cannot use
$variablewith theprintfformatting except for%%
- To inject nested object values use you can supply a keyPath i.e.
- Generate unique test titles by positionally injecting parameters with
-
fn:Functionthe suite of tests to be run, this is the function that will receive the parameters in each row as function arguments. -
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.
示例:
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- First row of variable name column headings separated with
| - One or more subsequent rows of data supplied as template literal expressions using
${value}syntax.
- First row of variable name column headings separated with
name:Stringthe title of the test suite, use$variableto inject test data into the suite title from the tagged template expressions, and$#for the index of the row.- To inject nested object values use you can supply a keyPath i.e.
$variable.path.to.value(only works for "own" properties, e.g.$variable.constructor.namewouldn't work)
- To inject nested object values use you can supply a keyPath i.e.
fn:Functionthe suite of tests to be run, this is the function that will receive the test data object.- 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.
示例:
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)
Also under the alias: fdescribe(name, fn)
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)
Also under the aliases: fdescribe.each(table)(name, fn) and fdescribe.each`table`(name, fn)
Use describe.only.each if you want to only run specific tests suites of data driven tests.
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.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)
Also under the alias: xdescribe(name, fn)
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
});
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)
Also under the aliases: xdescribe.each(table)(name, fn) and xdescribe.each`table`(name, fn)
Use describe.skip.each if you want to stop running a suite of data driven tests.
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.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)
Also under the alias: it(name, fn, timeout)
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. 你的整个测试可能是:
test('did not rain', () => {
expect(inchesOfRain()).toBe(0);
});
第一个参数是测试名称; 第二个参数是包含测试期望的函数。 The third argument (optional) is timeout (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds.
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');
});
});
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.
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)
Also under the alias: it.concurrent(name, fn, timeout)
test.concurrent is considered experimental - see here for details on missing features and other issues.
Use test.concurrent if you want the test to run concurrently.
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);
});
Use the maxConcurrency configuration option to prevent Jest from executing more than the specified amount of tests at the same time.