Jest
npm install @tracera/jest
已在 Node.js 22.19–26.12 和 Jest 30–30.5 上测试(见 自动化测试适配器)。@tracera/jest。
在 jest.config.cjs(或你的 Jest 配置)中:
module.exports = {
testEnvironment: 'node',
setupFilesAfterEnv: ['@tracera/jest/setup'],
reporters: ['default', '@tracera/jest/reporter'],
};
环境变量、运行模式与重试见 自动化测试适配器。
重试时 Env 键:JEST_RETRY。
绑定 testCaseId 与 autotestName
从 @jest/globals 导入 test、expect 和 hooks(或使用 Jest 注入的全局变量),从 @tracera/jest 导入 tracera、annotations 和 skip。加载 @tracera/jest/setup,以便步骤与绑定可配合标准 Jest API 使用。
在声明时(推荐 — 即使测试提前跳过也会绑定):
import { test, expect } from '@jest/globals';
import { annotations } from '@tracera/jest';
test(
'login',
annotations(42, 'e2e/login', async () => {
expect(true).toBe(true);
}),
);
在测试中(若 annotations 已绑定用例则可省略):
import { test, expect } from '@jest/globals';
import { tracera } from '@tracera/jest';
test('login', async () => {
tracera.testCase(42, 'e2e/login');
expect(true).toBe(true);
});
跳过
若事先已知应跳过 — 使用 test.skip 或 describe.skip。若 skip 条件在测试内计算 — 使用本包的 skip:Jest 没有 test.skip(reason)。
import { test } from '@jest/globals';
import { annotations, skip } from '@tracera/jest';
test(
'login',
annotations(42, 'e2e/login', () => {
if (!process.env.READY) skip('env not ready');
// …
}),
);
步骤
使用 tracera.step:调用 tracera.step(title, fn),在类方法上使用装饰器 @tracera.step("…"),或 tracera.step("…")(fn)。装饰器标题中的 {name} / {0} 从方法参数填入;也可以传入返回标题的函数。调用形式不会填充 {name} / {0}——请传入已拼好的标题字符串。会等待异步方法与 Promise。 来自 @jest/globals 的标准 beforeEach / afterEach 已仪器化:其中的步骤进入结果的 准备 / 清理。套件级钩子(如 beforeAll / afterAll)不会上报。
import { test, beforeEach, afterEach } from '@jest/globals';
import { tracera } from '@tracera/jest';
beforeEach(async () => {
await tracera.step('open shop', async () => {
// …
});
});
test('checkout', async () => {
tracera.testCase(10, 'e2e/checkout');
await tracera.step('add to cart', async () => {
// …
});
});
afterEach(async () => {
await tracera.step('cleanup', async () => {
// …
});
});
方法上的装饰器:
import { tracera } from '@tracera/jest';
class Cart {
@tracera.step('add {item}')
async addToCart(item: string) {
// …
}
}
注释、错误与附件
评论、错误与附件:自动化测试适配器。
import { test } from '@jest/globals';
import { tracera } from '@tracera/jest';
test('login', async () => {
tracera.testCase(42, 'e2e/login');
tracera.comment('result-level note');
tracera.error('result-level error text');
await tracera.step('open login', async () => {
tracera.comment('landed on login');
tracera.attachment({
fileName: 'suite-log.txt',
mimeType: 'text/plain',
data: new TextEncoder().encode('finished login flow'),
});
});
});
参数化测试
使用 test.each 时,用 annotations(id, 'login as {login}', fn) 包裹回调——对象行的字段会填入 {login} 等占位符。
import { test, expect } from '@jest/globals';
import { annotations } from '@tracera/jest';
test.each([{ login: 'ok' }, { login: 'sso' }])(
'login as $login',
annotations(42, 'login as {login}', async ({ login }) => {
expect(login).toBeTruthy();
}),
);