Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
6223563
feat: init projects config
9aoy Jul 23, 2025
2c7175e
fix: merge conflict
9aoy Jul 23, 2025
8a6f5d6
Merge branch 'main' of https://github.com/web-infra-dev/rstest into p…
9aoy Jul 24, 2025
d2b564a
feat: support test projects
9aoy Jul 25, 2025
dc73f68
fix: setupFiles
9aoy Jul 25, 2025
434eaaf
fix: merge conflict
9aoy Jul 25, 2025
e230567
feat: support glob pattern
9aoy Jul 25, 2025
3a42499
fix: should throw error when project not found
9aoy Jul 25, 2025
bf5a5e6
feat: should run test failed when test file not found
9aoy Jul 29, 2025
3ac39e0
Merge branch 'main' of https://github.com/web-infra-dev/rstest into p…
9aoy Jul 29, 2025
a0ad3f0
fix: merge conflict
9aoy Jul 29, 2025
83105ff
fix: tests
9aoy Jul 29, 2025
afc83ef
perf: reuse pool
9aoy Jul 29, 2025
1855377
fix: merge conflict
9aoy Aug 1, 2025
32a2f1c
fix: merge conflict
9aoy Aug 8, 2025
146adf6
fix: lint
9aoy Aug 11, 2025
446a423
fix: formatEnvironmentName
9aoy Aug 11, 2025
b2cb773
fix: merge conflict
9aoy Aug 11, 2025
94d1279
fix: project rootPath
9aoy Aug 11, 2025
1d7d7fc
fix: merge conflict
9aoy Aug 25, 2025
3370a75
fix: should not inherit root config by default
9aoy Aug 25, 2025
1841fe4
docs: add projects config
9aoy Aug 25, 2025
32ad196
fix: merge conflict
9aoy Aug 25, 2025
863ede7
fix: update `no test files found` log
9aoy Aug 25, 2025
cc74f9e
fix: update log
9aoy Aug 26, 2025
3ca6e0b
Update website/docs/zh/config/test/projects.mdx
9aoy Aug 26, 2025
e7a861f
Update website/docs/en/config/test/projects.mdx
fi3ework Aug 26, 2025
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
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,4 @@ jobs:

- name: E2E Test
if: steps.changes.outputs.changed == 'true'
run: pnpm run e2e && pnpm run test:example
run: pnpm run e2e
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
"build": "cross-env NX_DAEMON=false nx run-many -t build --exclude @examples/* @rstest/tests-* --parallel=10",
"e2e": "cd tests && pnpm test",
"test": "rstest run",
"test:example": "pnpm --filter @examples/* test",
"change": "changeset",
"changeset": "changeset",
"check-dependency-version": "pnpx check-dependency-version-consistency . && echo",
Expand Down
107 changes: 19 additions & 88 deletions packages/core/src/cli/commands.ts
Original file line number Diff line number Diff line change
@@ -1,44 +1,16 @@
import type { LoadConfigOptions } from '@rsbuild/core';
import cac, { type CAC } from 'cac';
import { normalize } from 'pathe';
import { isCI } from 'std-env';
import { loadConfig } from '../config';
import type {
ListCommandOptions,
RstestCommand,
RstestConfig,
RstestInstance,
} from '../types';
import { castArray, formatError, getAbsolutePath } from '../utils/helper';
import { formatError } from '../utils/helper';
import { logger } from '../utils/logger';
import type { CommonOptions } from './init';
import { showRstest } from './prepare';

type CommonOptions = {
root?: string;
config?: string;
configLoader?: LoadConfigOptions['loader'];
globals?: boolean;
isolate?: boolean;
include?: string[];
exclude?: string[];
passWithNoTests?: boolean;
printConsoleTrace?: boolean;
disableConsoleIntercept?: boolean;
update?: boolean;
testNamePattern?: RegExp | string;
testTimeout?: number;
hookTimeout?: number;
testEnvironment?: string;
clearMocks?: boolean;
resetMocks?: boolean;
restoreMocks?: boolean;
unstubGlobals?: boolean;
unstubEnvs?: boolean;
retry?: number;
maxConcurrency?: number;
slowTestThreshold?: number;
};

const applyCommonOptions = (cli: CAC) => {
cli
.option(
Expand Down Expand Up @@ -105,60 +77,6 @@ const applyCommonOptions = (cli: CAC) => {
);
};

export async function initCli(options: CommonOptions): Promise<{
config: RstestConfig;
configFilePath: string | null;
}> {
const cwd = process.cwd();
const root = options.root ? getAbsolutePath(cwd, options.root) : cwd;

const { content: config, filePath: configFilePath } = await loadConfig({
cwd: root,
path: options.config,
configLoader: options.configLoader,
});

const keys: (keyof CommonOptions & keyof RstestConfig)[] = [
'root',
'globals',
'isolate',
'passWithNoTests',
'update',
'testNamePattern',
'testTimeout',
'hookTimeout',
'clearMocks',
'resetMocks',
'restoreMocks',
'unstubEnvs',
'unstubGlobals',
'retry',
'slowTestThreshold',
'maxConcurrency',
'printConsoleTrace',
'disableConsoleIntercept',
'testEnvironment',
];
for (const key of keys) {
if (options[key] !== undefined) {
(config[key] as any) = options[key];
}
}

if (options.exclude) {
config.exclude = castArray(options.exclude);
}

if (options.include) {
config.include = castArray(options.include);
}

return {
config,
configFilePath,
};
}

export function setupCommands(): void {
const cli = cac('rstest');

Expand Down Expand Up @@ -186,9 +104,17 @@ export function setupCommands(): void {
) => {
let rstest: RstestInstance | undefined;
try {
const { config } = await initCli(options);
const { initCli } = await import('./init');
const { config, projects } = await initCli(options);
const { createRstest } = await import('../core');
rstest = createRstest(config, command, filters.map(normalize));
rstest = createRstest(
{
config,
projects,
},
command,
filters.map(normalize),
);
await rstest.runTests();
} catch (err) {
for (const reporter of rstest?.context.reporters || []) {
Expand Down Expand Up @@ -224,9 +150,14 @@ export function setupCommands(): void {
options: CommonOptions & ListCommandOptions,
) => {
try {
const { config } = await initCli(options);
const { initCli } = await import('./init');
const { config, projects } = await initCli(options);
const { createRstest } = await import('../core');
const rstest = createRstest(config, 'list', filters.map(normalize));
const rstest = createRstest(
{ config, projects },
'list',
filters.map(normalize),
);
await rstest.listTests({
filesOnly: options.filesOnly,
json: options.json,
Expand Down
170 changes: 170 additions & 0 deletions packages/core/src/cli/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
import { existsSync, readFileSync } from 'node:fs';
import type { LoadConfigOptions } from '@rsbuild/core';
import { basename, resolve } from 'pathe';
import { isDynamicPattern } from 'tinyglobby';
import { loadConfig } from '../config';
import type { Project, RstestConfig } from '../types';
import { castArray, getAbsolutePath } from '../utils/helper';

export type CommonOptions = {
root?: string;
config?: string;
configLoader?: LoadConfigOptions['loader'];
globals?: boolean;
isolate?: boolean;
include?: string[];
exclude?: string[];
passWithNoTests?: boolean;
printConsoleTrace?: boolean;
disableConsoleIntercept?: boolean;
update?: boolean;
testNamePattern?: RegExp | string;
testTimeout?: number;
hookTimeout?: number;
testEnvironment?: string;
clearMocks?: boolean;
resetMocks?: boolean;
restoreMocks?: boolean;
unstubGlobals?: boolean;
unstubEnvs?: boolean;
retry?: number;
maxConcurrency?: number;
slowTestThreshold?: number;
};

async function resolveConfig(
options: CommonOptions & Required<Pick<CommonOptions, 'root'>>,
): Promise<{
config: RstestConfig;
configFilePath: string | null;
}> {
const { content: config, filePath: configFilePath } = await loadConfig({
cwd: options.root,
path: options.config,
configLoader: options.configLoader,
});

const keys: (keyof CommonOptions & keyof RstestConfig)[] = [
'root',
'globals',
'isolate',
'passWithNoTests',
'update',
'testNamePattern',
'testTimeout',
'hookTimeout',
'clearMocks',
'resetMocks',
'restoreMocks',
'unstubEnvs',
'unstubGlobals',
'retry',
'slowTestThreshold',
'maxConcurrency',
'printConsoleTrace',
'disableConsoleIntercept',
'testEnvironment',
];
for (const key of keys) {
if (options[key] !== undefined) {
(config[key] as any) = options[key];
}
}

if (options.exclude) {
config.exclude = castArray(options.exclude);
}

if (options.include) {
config.include = castArray(options.include);
}

return {
config,
configFilePath,
};
}

export async function resolveProjects({
config,
root,
options,
}: {
config: RstestConfig;
root: string;
options: CommonOptions;
}): Promise<Project[]> {
const projects: Project[] = [];

const getDefaultProjectName = (dir: string) => {
const pkgJsonPath = resolve(dir, 'package.json');
const name = existsSync(pkgJsonPath)
? JSON.parse(readFileSync(pkgJsonPath, 'utf-8')).name
: '';

if (typeof name !== 'string' || !name) {
return basename(dir);
}
return name;
};

const names = new Set<string>();

for (const project of config.projects || []) {
const projectStr = project.replace('<rootDir>', root);

if (isDynamicPattern(projectStr)) {
// TODO
throw `Dynamic project pattern (${project}) is not supported. Please use static paths.`;
Copy link
Preview

Copilot AI Jul 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Throwing a string instead of an Error object is not a best practice. Consider using throw new Error() for better error handling and stack traces.

Copilot uses AI. Check for mistakes.

}

const absolutePath = getAbsolutePath(root, projectStr);

const { config, configFilePath } = await resolveConfig({
...options,
root: absolutePath,
});

config.name ??= getDefaultProjectName(absolutePath);

projects.push({
config,
configFilePath,
});

if (names.has(config.name)) {
const conflictProjects = projects.filter(
(p) => p.config.name === config.name,
);
throw `Project name "${config.name}" is already used. Please ensure all projects have unique names.
Conflicting projects:
${conflictProjects.map((p) => `- ${p.configFilePath || p.config.root}`).join('\n')}
`;
Copy link
Preview

Copilot AI Jul 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Throwing a string instead of an Error object is not a best practice. Consider using throw new Error() for better error handling and stack traces.

Suggested change
throw `Project name "${config.name}" is already used. Please ensure all projects have unique names.
Conflicting projects:
${conflictProjects.map((p) => `- ${p.configFilePath || p.config.root}`).join('\n')}
`;
throw new Error(`Project name "${config.name}" is already used. Please ensure all projects have unique names.
Conflicting projects:
${conflictProjects.map((p) => `- ${p.configFilePath || p.config.root}`).join('\n')}`);

Copilot uses AI. Check for mistakes.

}

names.add(config.name);
}
return projects;
}

export async function initCli(options: CommonOptions): Promise<{
config: RstestConfig;
configFilePath: string | null;
projects: Project[];
}> {
const cwd = process.cwd();
const root = options.root ? getAbsolutePath(cwd, options.root) : cwd;

const { config, configFilePath } = await resolveConfig({
...options,
root,
});

const projects = await resolveProjects({ config, root, options });

return {
config,
configFilePath,
projects,
};
}
32 changes: 30 additions & 2 deletions packages/core/src/core/context.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import { SnapshotManager } from '@vitest/snapshot/manager';
import { isCI } from 'std-env';
import { withDefaultConfig } from '../config';
import { mergeRstestConfig, withDefaultConfig } from '../config';
import { DefaultReporter } from '../reporter';
import type { RstestCommand, RstestConfig, RstestContext } from '../types';
import type {
NormalizedConfig,
Project,
RstestCommand,
RstestConfig,
RstestContext,
} from '../types';
import { castArray, getAbsolutePath } from '../utils/helper';

const reportersMap = {
Expand Down Expand Up @@ -45,6 +51,7 @@ function createReporters(
export function createContext(
options: { cwd: string; command: RstestCommand },
userConfig: RstestConfig,
projects: Project[],
): RstestContext {
const { cwd, command } = options;
const rootPath = userConfig.root
Expand All @@ -59,6 +66,8 @@ export function createContext(
config: rstestConfig,
})
: [];

// TODO: project.snapshotManager ?
const snapshotManager = new SnapshotManager({
updateSnapshot: rstestConfig.update ? 'all' : isCI ? 'none' : 'new',
});
Expand All @@ -71,5 +80,24 @@ export function createContext(
snapshotManager,
originalConfig: userConfig,
normalizedConfig: rstestConfig,
projects: projects.length
? projects.map((project) => {
const config = mergeRstestConfig(
rstestConfig,
project.config,
) as NormalizedConfig;
return {
rootPath: config.root,
name: config.name,
normalizedConfig: config,
};
})
: [
{
rootPath,
name: rstestConfig.name,
normalizedConfig: rstestConfig,
},
],
};
}
Loading