Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion e2e/lifecycle/fixtures/beforeEach.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ describe('level A', () => {
expect(2 + 2).toBe(4);
});

beforeEach(() => {
beforeEach((ctx) => {
expect(ctx.task.name).toBe('it in level B-B');
console.log('[beforeEach] in level B-B');
});
});
Expand Down
2 changes: 1 addition & 1 deletion e2e/lifecycle/fixtures/onTestFailed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {

beforeEach(() => {
onTestFailed(({ task }) => {
console.log('[onTestFailed]', task.result.name);
console.log('[onTestFailed]', task.result?.name);
});
});
describe('level A', () => {
Expand Down
2 changes: 1 addition & 1 deletion e2e/scripts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ export async function runRstestCli({
});

onTestFailed?.(({ task }) => {
if (task.result.errors?.[0]) {
if (task.result?.errors?.[0]) {
task.result.errors![0]!.message +=
`\n\n--- CLI Log Start ---\n${cli.log}\n--- CLI Log End ---\n`;
}
Expand Down
29 changes: 14 additions & 15 deletions packages/core/src/runtime/runner/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,15 @@ export class TestRunner {

const cleanups: AfterEachListener[] = [];

const fixtureCleanups = await this.beforeRunTest(
test,
snapshotClient.getSnapshotState(testPath),
);
cleanups.push(...fixtureCleanups);

try {
for (const fn of parentHooks.beforeEachListeners) {
const cleanupFn = await fn();
const cleanupFn = await fn(test.context);
cleanupFn && cleanups.push(cleanupFn);
}
} catch (error) {
Expand All @@ -120,11 +126,6 @@ export class TestRunner {
if (result?.status !== 'fail') {
if (test.fails) {
try {
const fixtureCleanups = await this.beforeRunTest(
test,
snapshotClient.getSnapshotState(testPath),
);
cleanups.push(...fixtureCleanups);
await test.fn?.(test.context);
this.afterRunTest(test);

Expand Down Expand Up @@ -153,11 +154,6 @@ export class TestRunner {
}
} else {
try {
const fixtureCleanups = await this.beforeRunTest(
test,
snapshotClient.getSnapshotState(testPath),
);
cleanups.push(...fixtureCleanups);
if (test.fn) {
const fn = wrapTimeout({
name: 'test',
Expand Down Expand Up @@ -203,9 +199,10 @@ export class TestRunner {
.concat(cleanups)
.concat(test.onFinished);

test.context.task.result = result;
try {
for (const fn of afterEachFns) {
await fn({ task: { result } });
await fn(test.context);
}
} catch (error) {
result.status = 'fail';
Expand All @@ -216,7 +213,7 @@ export class TestRunner {
if (result.status === 'fail') {
for (const fn of [...test.onFailed].reverse()) {
try {
await fn({ task: { result } });
await fn(test.context);
} catch (error) {
result.errors ??= [];
result.errors.push(...formatTestError(error));
Expand Down Expand Up @@ -520,7 +517,7 @@ export class TestRunner {
}
}

private createTestContext(): TestContext {
private createTestContext(test: TestCase): TestContext {
const context = (() => {
throw new Error('done() callback is deprecated, use promise instead');
}) as unknown as TestContext;
Expand All @@ -529,6 +526,8 @@ export class TestRunner {

const current = this._test;

context.task = { name: test.name };

Object.defineProperty(context, 'expect', {
get: () => {
if (!_expect) {
Expand Down Expand Up @@ -620,7 +619,7 @@ export class TestRunner {
(globalThis as any)[GLOBAL_EXPECT],
);

const context = this.createTestContext();
const context = this.createTestContext(test);

const { cleanups } = await handleFixtures(test, context);

Expand Down
17 changes: 11 additions & 6 deletions packages/core/src/types/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,15 @@ import type {
import type { MaybePromise } from './utils';

export type TestContext = {
/**
* Metadata of the current test
*/
task: {
/** Test name provided by user */
name: string;
/** Result of the current test, undefined if the test is not run yet */
result?: TestResult;
};
expect: RstestExpect;
onTestFinished: RunnerAPI['onTestFinished'];
onTestFailed: RunnerAPI['onTestFailed'];
Expand Down Expand Up @@ -157,13 +166,9 @@ export type TestAPIs<ExtraContext = object> = TestAPI<ExtraContext> & {
}>;
};

export type OnTestFinishedHandler = (params: {
task: { result: Readonly<TestResult> };
}) => MaybePromise<void>;
export type OnTestFinishedHandler = (ctx: TestContext) => MaybePromise<void>;

export type OnTestFailedHandler = (params: {
task: { result: Readonly<TestResult> };
}) => MaybePromise<void>;
export type OnTestFailedHandler = (ctx: TestContext) => MaybePromise<void>;

export type RunnerAPI = {
describe: DescribeAPI;
Expand Down
11 changes: 7 additions & 4 deletions packages/core/src/types/testSuite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,16 @@ export type SuiteContext = {
};

export type AfterAllListener = (ctx: SuiteContext) => MaybePromise<void>;

export type BeforeAllListener = (
ctx: SuiteContext,
) => MaybePromise<void | AfterAllListener>;
export type AfterEachListener = (params: {
task: { result: Readonly<TestResult> };
}) => MaybePromise<void>;
export type BeforeEachListener = () => MaybePromise<void | AfterEachListener>;

export type AfterEachListener = (ctx: TestContext) => MaybePromise<void>;

export type BeforeEachListener = (
ctx: TestContext,
) => MaybePromise<void | AfterEachListener>;

export type TestSuiteInfo = {
testId: string;
Expand Down
6 changes: 3 additions & 3 deletions website/docs/en/api/test-api/hooks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ afterAll(async (ctx) => {

## beforeEach

- **Type:** `(fn: () => void | Promise<void>, timeout?: number) => void`
- **Type:** `(fn: (ctx: TestContext) => void | Promise<void>, timeout?: number) => void`

Runs before each test in the current suite.

Expand Down Expand Up @@ -81,7 +81,7 @@ beforeEach(async () => {

## afterEach

- **Type:** `(fn: (ctx: { task: { result: Readonly<TestResult> } }) => void | Promise<void>, timeout?: number) => void`
- **Type:** `(fn: (ctx: TestContext) => void | Promise<void>, timeout?: number) => void`

Runs after each test in the current suite.

Expand Down Expand Up @@ -139,7 +139,7 @@ test('test server', () => {
const server = startServer();

onTestFailed(({ task }) => {
console.log(task.result.errors);
console.log(task.result?.errors);
});

server.listen(3000, () => {
Expand Down
9 changes: 9 additions & 0 deletions website/docs/en/api/test-api/test.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,15 @@ testWithUser('has user in context', ({ user, expect }) => {

```ts
export interface TestContext {
/**
* Metadata of the current test
*/
task: {
/** Test name provided by user */
name: string;
/** Result of the current test, undefined if the test is not run yet */
result?: TestResult;
};
/** The `expect` API bound to the current test */
expect: Expect;
/** The `onTestFinished` hook bound to the current test */
Expand Down
6 changes: 3 additions & 3 deletions website/docs/zh/api/test-api/hooks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ afterAll(async (ctx) => {

## beforeEach

- **类型:** `(fn: () => void | Promise<void>, timeout?: number) => void`
- **类型:** `(fn: (ctx: TestContext) => void | Promise<void>, timeout?: number) => void`

在当前套件的每个测试之前运行。

Expand Down Expand Up @@ -81,7 +81,7 @@ beforeEach(async () => {

## afterEach

- **类型:** `(fn: (ctx: { task: { result: Readonly<TestResult> } }) => void | Promise<void>, timeout?: number) => void`
- **类型:** `(fn: (ctx: TestContext) => void | Promise<void>, timeout?: number) => void`

在当前套件的每个测试之后运行。

Expand Down Expand Up @@ -139,7 +139,7 @@ test('test server', () => {
const server = startServer();

onTestFailed(({ task }) => {
console.log(task.result.errors);
console.log(task.result?.errors);
});

server.listen(3000, () => {
Expand Down
9 changes: 9 additions & 0 deletions website/docs/zh/api/test-api/test.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,15 @@ testWithUser('has user in context', ({ user, expect }) => {

```ts
export interface TestContext {
/**
* Metadata of the current test
*/
task: {
/** Test name provided by user */
name: string;
/** Result of the current test, undefined if the test is not run yet */
result?: TestResult;
};
/** The `expect` API bound to the current test */
expect: Expect;
/** The `onTestFinished` hook bound to the current test */
Expand Down
Loading