close
logo
Rstest
指南
配置
API
English
简体中文
指南
配置
API
English
简体中文
logo
Rstest
Overview

Test API

Expect
Test
Describe
Hooks

Rstest Utility

Mock modules
Mock functions
MockInstance
Fake timers
Utilities
📝 在 GitHub 上编辑此页
上一页Expect
下一页Describe

#Test

test 用于定义一个测试用例,支持链式调用和 fixture 扩展。

别名:it。

#test

  • 类型: (name: string, fn: (testContext: TestContext) => void | Promise<void>, timeout?: number) => void

定义一个测试用例。

import { expect, test } from '@rstest/core';

test('should add two numbers correctly', () => {
  expect(1 + 1).toBe(2);
  expect(1 + 2).toBe(3);
});

#test.only

只运行测试文件中的某些测试。

test.only('run only this test', () => {
  // ...
});

#test.skip

跳过某些测试。

test.skip('skip this test', () => {
  // ...
});

#test.todo

将某些测试标记为待办。

test.todo('should implement this test');

#test.each

  • 类型: test.each(cases: ReadonlyArray<T>)(name: string, fn: (param: T) => void | Promise<void>, timeout?: number) => void

对提供的数组中的每一项运行相同的测试逻辑。

test.each([
  { a: 1, b: 2, sum: 3 },
  { a: 2, b: 2, sum: 4 },
])('adds $a + $b', ({ a, b, sum }) => {
  expect(a + b).toBe(sum);
});

#test.for

  • 类型: test.for(cases: ReadonlyArray<T>)(name: string, fn: (param: T, testContext: TestContext) => void | Promise<void>, timeout?: number) => void

test.each 的替代方案,提供 TestContext。

test.for([
  { a: 1, b: 2 },
  { a: 2, b: 2 },
])('adds $a + $b', ({ a, b }, { expect }) => {
  expect(a + b).matchSnapshot();
});

#test.fails

标记该测试预期会失败。

test.fails('should fail', () => {
  throw new Error('This test is expected to fail');
});

#test.concurrent

并发运行连续带有 concurrent 标记的测试。

describe('suite', () => {
  test('serial test', async () => {
    /* ... */
  });
  test.concurrent('concurrent test 1', async () => {
    /* ... */
  });
  test.concurrent('concurrent test 2', async () => {
    /* ... */
  });
  test('serial test 1', async () => {
    /* ... */
  });
});

#test.sequential

顺序(串行)运行测试(默认行为)。

describe('suite', () => {
  test('serial test', async () => {
    /* ... */
  });
  test('serial test 1', async () => {
    /* ... */
  });
});

#test.runIf

仅当条件为真时才运行该测试。

test.runIf(process.env.RUN_EXTRA === '1')('conditionally run', () => {
  // ...
});

#test.skipIf

当条件为真时跳过该测试。

test.skipIf(process.platform === 'win32')('skip on Windows', () => {
  // ...
});

#test.extend

  • 类型: test.extend(fixtures: Fixtures)

通过自定义 fixture 扩展测试上下文。

const testWithUser = test.extend({
  user: async ({}, use) => {
    await use({ name: 'Alice' });
  },
});

testWithUser('has user in context', ({ user, expect }) => {
  expect(user.name).toBe('Alice');
});

#Types

#TestContext

TestContext 提供一些和当前测试有关的 API、上下文信息,以及自定义的 fixture。

export interface TestContext {
  /** The `expect` API bound to the current test */
  expect: Expect;
  /** The `onTestFinished` hook bound to the current test */
  onTestFinished: OnTestFinished;
  /** The `onTestFailed` hook bound to the current test */
  onTestFailed: OnTestFailed;
}

你也可以通过 test.extend 方法通过自定义 fixture 的方式来扩展测试上下文。