Skip to content

feat: support test projects #420

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 8 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 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
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')}
`;
Comment on lines +171 to +174
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