跳至主要內容
版本:29.7

全域

在您的測試檔案中,Jest 會將這些方法和物件放入全域環境中。您不需要 require 或 import 任何內容即可使用它們。但是,如果您偏好明確的 import,您可以執行 import {describe, expect, test} from '@jest/globals'

資訊

此頁面的 TypeScript 範例僅在您明確 import Jest API 時才會按文件運作

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

請參閱 入門 指南,了解如何使用 TypeScript 設定 Jest 的詳細資訊。

方法


參考

afterAll(fn, 超時)

在這個檔案中的所有測試完成後執行一個函式。如果函式回傳一個承諾或是一個產生器,Jest 會等到承諾解決後才繼續執行。

選擇性地,你可以提供一個 超時(以毫秒為單位)來指定在中斷之前要等待多久。預設超時是 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 區塊中,它會在 describe 區塊的最後執行。

如果你想在每個測試後執行一些清除,而不是在所有測試後執行,請改用 afterEach

afterEach(fn, 超時)

在這個檔案中的每個測試完成後執行一個函式。如果函式回傳一個承諾或是一個產生器,Jest 會等到承諾解決後才繼續執行。

選擇性地,你可以提供一個 超時(以毫秒為單位)來指定在中斷之前要等待多久。預設超時是 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

如果 afterEachdescribe 區塊內,它只會在這個 describe 區塊內的測試執行後執行。

如果你想在所有測試執行後只執行一次清理,請改用 afterAll

beforeAll(fn, timeout)

在這個檔案中的任何測試執行前執行函式。如果函式傳回承諾或產生器,Jest 會等到承諾解決後才執行測試。

選擇性地,你可以提供一個 超時(以毫秒為單位)來指定在中斷之前要等待多久。預設超時是 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 會等到承諾解決,因此你也可以進行非同步設定。

如果 beforeAlldescribe 區塊內,它會在 describe 區塊開始時執行。

如果你想在每個測試執行前執行某些操作,而不是在任何測試執行前執行,請改用 beforeEach

beforeEach(fn, timeout)

在這個檔案中的每個測試執行前執行函式。如果函式傳回承諾或產生器,Jest 會等到承諾解決後才執行測試。

選擇性地,你可以提供一個 超時(以毫秒為單位)來指定在中斷之前要等待多久。預設超時是 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 確保為每個測試重設資料庫。

如果 beforeEachdescribe 區塊內,它會為 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.eachdescribe.each 讓您可以撰寫測試套件一次,並傳入資料。

describe.each 可使用兩個 API

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

  • table:陣列的陣列,其中包含傳入每列 fn 的參數。如果您傳入基本資料的 1D 陣列,內部會將其對應到一個表格,例如 [1, 2, 3] -> [[1], [2], [3]]

  • name:測試套件的標題 String

    • 透過使用 printf 格式化,依據位置插入參數,產生獨特的測試標題
      • %p - pretty-format
      • %s- 字串。
      • %d- 數字。
      • %i - 整數。
      • %f - 浮點值。
      • %j - JSON。
      • %o - 物件。
      • %# - 測試案例的索引。
      • %% - 單一百分比符號 ('%')。這不會使用參數。
    • 或透過使用 $variable,插入測試案例物件的屬性,產生獨特的測試標題
      • 若要插入巢狀物件值,您可以提供 keyPath,例如 $variable.path.to.value
      • 您可以使用 $# 插入測試案例的索引
      • 您無法將 $variableprintf 格式化一起使用,但 %% 除外
  • 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:標記範本文字
    • 變數名稱欄位標題的第一列,以 | 分隔
    • 使用 ${value} 語法提供的一或多列後續資料,作為範本文字表達式。
  • name:測試套件的標題 String,使用 $variable 從標記範本表達式將測試資料插入套件標題,並使用 $# 作為列的索引。
    • 若要插入巢狀物件值,您可以提供 keyPath,例如 $variable.path.to.value
  • 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 提供兩個 API

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 區塊仍會執行。如果您有一些設定也應該略過,請在 beforeAllbeforeEach 區塊中執行。

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

亦有別名:xdescribe.each(table)(name, fn)xdescribe.each`table`(name, fn)

如果您想停止執行資料驅動測試套件,請使用 describe.skip.each

describe.skip.each 提供兩個 API

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 會等到 promise 解決後才讓測試完成。例如,假設 fetchBeverageList() 傳回一個 promise,而這個 promise 應該會解決為一個包含 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.eachtest.each 允許你寫一次測試並傳入資料,所有測試都會非同步執行。

test.concurrent.each 提供兩種 API

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

  • table:包含傳遞給每個列測試 fn 的引數的陣列陣列。如果您傳入基本型別的 1D 陣列,內部會將其對應到表格,例如 [1, 2, 3] -> [[1], [2], [3]]
  • name字串測試區塊的標題。
    • 透過使用 printf 格式化,依據位置插入參數,產生獨特的測試標題
      • %p - pretty-format
      • %s- 字串。
      • %d- 數字。
      • %i - 整數。
      • %f - 浮點值。
      • %j - JSON。
      • %o - 物件。
      • %# - 測試案例的索引。
      • %% - 單一百分比符號 ('%')。這不會使用參數。
  • fn函式要執行的測試,這是會將每個列的參數接收為函式引數的函式,這必須是非同步函式
  • 選擇性地,您可以提供 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:標記範本文字
    • 變數名稱欄位標題的第一列,以 | 分隔
    • 使用 ${value} 語法提供的一或多列後續資料,作為範本文字表達式。
  • name字串測試的標題,使用 $variable 將測試資料注入來自標記樣板運算式的測試標題。
    • 若要插入巢狀物件值,您可以提供 keyPath,例如 $variable.path.to.value
  • fn函式要執行的測試,這是會接收測試資料物件的函式,這必須是非同步函式
  • 選擇性地,您可以提供 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 提供兩種 API

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 提供兩種 API

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.each`table`(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.each`table`(name, fn)

如果你持續使用不同的資料重複相同的測試,請使用 test.eachtest.each 允許你撰寫一次測試,並傳入資料。

test.each 提供兩種 API

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

  • table:包含傳遞給每個列測試 fn 的引數的陣列陣列。如果您傳入基本型別的 1D 陣列,內部會將其對應到表格,例如 [1, 2, 3] -> [[1], [2], [3]]
  • name字串測試區塊的標題。
    • 透過使用 printf 格式化,依據位置插入參數,產生獨特的測試標題
      • %p - pretty-format
      • %s- 字串。
      • %d- 數字。
      • %i - 整數。
      • %f - 浮點值。
      • %j - JSON。
      • %o - 物件。
      • %# - 測試案例的索引。
      • %% - 單一百分比符號 ('%')。這不會使用參數。
    • 或透過使用 $variable,插入測試案例物件的屬性,產生獨特的測試標題
      • 若要插入巢狀物件值,您可以提供 keyPath,例如 $variable.path.to.value
      • 您可以使用 $# 插入測試案例的索引
      • 您無法將 $variableprintf 格式化一起使用,但 %% 除外
  • fn:要執行的測試的 Function,此函式將接收每一列的參數作為函式引數。
  • 選擇性地,您可以提供 timeout(以毫秒為單位),用於指定在中止之前要等待每一列的時間。預設逾時時間為 5 秒。

範例

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.each`table`(name, fn, timeout)

  • table:標記範本文字
    • 變數名稱欄位標題的第一列,以 | 分隔
    • 使用 ${value} 語法提供的一或多列後續資料,作為範本文字表達式。
  • name字串測試的標題,使用 $variable 將測試資料注入來自標記樣板運算式的測試標題。
    • 若要插入巢狀物件值,您可以提供 keyPath,例如 $variable.path.to.value
  • fn:要執行的測試的 Function,此函式將接收測試資料物件。
  • 選擇性地,您可以提供 timeout(以毫秒為單位),用於指定在中止之前要等待每一列的時間。預設逾時時間為 5 秒。

範例

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)

注意

這僅適用於預設的 jest-circus 執行器。

當你撰寫測試並預期它會失敗時,請使用 test.failing。這些測試的行為與一般測試相反。如果 failing 測試會擲回任何錯誤,則它會通過。如果它沒有擲回,則它會失敗。

提示

你可以使用這種類型的測試,例如以 BDD 方式撰寫程式碼時。在這種情況下,測試不會顯示為失敗,直到它們通過為止。然後你可以移除 failing 修飾詞,讓它們通過。

即使你不知道如何修正錯誤,這也可以是為專案提供失敗測試的好方法。

範例

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.each`table`(name, fn)

注意

這僅適用於預設的 jest-circus 執行器。

您也可以在 failing 後面加上 each,一次執行多個測試。

範例

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)

注意

這僅適用於預設的 jest-circus 執行器。

如果您只想執行特定的失敗測試,請使用 test.only.failing

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

別名:it.skip.failing(name, fn, timeout)xit.failing(name, fn, timeout)xtest.failing(name, fn, timeout)

注意

這僅適用於預設的 jest-circus 執行器。

如果您想略過執行特定的失敗測試,請使用 test.skip.failing

test.only(name, fn, timeout)

別名:it.only(name, fn, timeout)fit(name, fn, timeout)

當您偵錯大型測試檔案時,通常只會想執行測試的子集。您可以使用 .only 指定在該測試檔案中您唯一想執行的測試。

選擇性地,你可以提供一個 超時(以毫秒為單位)來指定在中斷之前要等待多久。預設超時是 5 秒。

例如,假設您有這些測試

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

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

由於使用 test.only 執行,因此在該測試檔案中,只有「it is raining」測試會執行。

通常您不會使用 test.only 將程式碼提交到原始碼控制中,而是用於偵錯,並在修復有問題的測試後將其移除。

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

別名:it.only.each(table)(name, fn)fit.each(table)(name, fn)it.only.each`table`(name, fn)fit.each`table`(name, fn)

如果你只想使用不同的測試資料執行特定測試,請使用 test.only.each

test.only.each 提供兩個 API

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.each`table`(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)

維護大型程式碼庫時,你可能會發現某個測試因故暫時中斷。如果你想略過執行此測試,但又不想刪除此程式碼,可以使用 test.skip 指定要略過的測試。

例如,假設您有這些測試

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

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

只有「下雨了」測試會執行,因為其他測試已使用 test.skip 執行。

你可以將測試註解掉,但使用 test.skip 通常會好一點,因為它會保留縮排和語法突顯。

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

別名: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)xtest.each`table`(name, fn)

如果你想停止執行一組資料驅動測試,請使用 test.skip.each

test.skip.each 提供兩個 API

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.each`table`(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)

當你計畫撰寫測試時,請使用 test.todo。這些測試會在最後的摘要輸出中突顯,讓你了解還有多少測試需要完成。

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

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

如果您傳遞測試回呼函式給 test.todo,它會擲回錯誤。如果您已實作測試,但不想執行它,請改用 test.skip

TypeScript 用法

資訊

此頁面的 TypeScript 範例僅在您明確 import Jest API 時才會按文件運作

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

請參閱 入門 指南,了解如何使用 TypeScript 設定 Jest 的詳細資訊。

.each

.each 修改器提供幾種不同的方式來定義測試案例的表格。有些 API 與傳遞給 describetest 回呼函式的引數類型推論有關。讓我們來看看每一個。

注意

為簡化起見,範例選擇 test.each,但類型推論在所有可以使用 .each 修改器的情況下都是相同的:describe.eachtest.concurrent.only.eachtest.skip.each 等。

物件陣列

物件陣列 API 最為詳細,但它讓類型推論變得輕鬆。table 可以內嵌

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`
});

或另外宣告為變數

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`
});

陣列陣列

陣列陣列樣式可以順利使用內嵌表格

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`
});

但是,如果表格宣告為獨立變數,則必須將其類型設定為元組陣列才能進行正確的類型推論(僅當一列的所有元素都是同類型時才不需要這樣做)

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`
});

範本字串

如果所有值都是同類型,範本字串 API 會正確設定引數類型

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`
});

否則,它會需要一般類型引數

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`
});