Skip to content

Commit

Permalink
test: pass expect in test env (#6579)
Browse files Browse the repository at this point in the history
* test: pass expect in test env

* test: pass expect in test env

* test: pass expect in test env
  • Loading branch information
LingyuCoder authored May 20, 2024
1 parent 093a237 commit 5fbabcf
Show file tree
Hide file tree
Showing 23 changed files with 69 additions and 63 deletions.
14 changes: 7 additions & 7 deletions packages/rspack-test-tools/etc/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ export function createWatchCase(name: string, src: string, dist: string, temp: s
export class DefaultsConfigTaskProcessor extends SimpleTaskProcessor<ECompilerType.Rspack> {
constructor(_defaultsConfigOptions: IDefaultsConfigProcessorOptions);
// (undocumented)
static addSnapshotSerializer(): void;
static addSnapshotSerializer(expectImpl: jest.Expect): void;
// (undocumented)
after(context: ITestContext): Promise<void>;
// (undocumented)
Expand Down Expand Up @@ -249,7 +249,7 @@ export enum EEsmMode {
export class ErrorTaskProcessor<T extends ECompilerType> extends SimpleTaskProcessor<T> {
constructor(_errorOptions: IErrorTaskProcessorOptions<T>);
// (undocumented)
static addSnapshotSerializer(): void;
static addSnapshotSerializer(expectImpl: jest.Expect): void;
// (undocumented)
check(env: ITestEnv, context: ITestContext): Promise<void>;
// (undocumented)
Expand Down Expand Up @@ -281,7 +281,7 @@ export class HookCasesContext extends TestContext {
// @internal (undocumented)
_addSnapshot(content: unknown, name: string, group: string | number): void;
// @internal (undocumented)
collectSnapshots(options?: {
collectSnapshots(env: ITestEnv, options?: {
diff: {};
}): Promise<void>;
// (undocumented)
Expand Down Expand Up @@ -335,8 +335,6 @@ export interface IBasicGlobalContext {
// (undocumented)
console: Console;
// (undocumented)
expect: jest.Expect;
// (undocumented)
setTimeout: typeof setTimeout;
}

Expand Down Expand Up @@ -716,6 +714,8 @@ export interface ITestEnv {
// (undocumented)
beforeEach: (...args: any[]) => void;
// (undocumented)
expect: jest.Expect;
// (undocumented)
it: (...args: any[]) => void;
}

Expand Down Expand Up @@ -932,7 +932,7 @@ export class RspackHotStepProcessor extends RspackHotProcessor {
// (undocumented)
protected _hotOptions: IRspackHotProcessorOptions;
// (undocumented)
protected matchStepSnapshot(context: ITestContext, step: number, stats: StatsCompilation, runtime?: THotStepRuntimeData): void;
protected matchStepSnapshot(env: ITestEnv, context: ITestContext, step: number, stats: StatsCompilation, runtime?: THotStepRuntimeData): void;
// (undocumented)
run(env: ITestEnv, context: ITestContext): Promise<void>;
}
Expand Down Expand Up @@ -1026,7 +1026,7 @@ export class SnapshotProcessor<T extends ECompilerType> extends BasicTaskProcess
export class StatsAPITaskProcessor<T extends ECompilerType> extends SimpleTaskProcessor<T> {
constructor(_statsAPIOptions: IStatsAPITaskProcessorOptions<T>);
// (undocumented)
static addSnapshotSerializer(): void;
static addSnapshotSerializer(expectImpl: jest.Expect): void;
// (undocumented)
check(env: ITestEnv, context: ITestContext): Promise<void>;
// (undocumented)
Expand Down
2 changes: 1 addition & 1 deletion packages/rspack-test-tools/src/case/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ async function run(name: string, processor: ITestProcessor) {
} catch (e: unknown) {
context.emitError(name, e as Error);
} finally {
await processor.check?.(null as unknown as ITestEnv, context);
await processor.check?.({ expect, it, beforeEach, afterEach }, context);
await processor.after?.(context);
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/rspack-test-tools/src/case/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export function createErrorCase(
testConfig: string
) {
if (!addedSerializer) {
ErrorTaskProcessor.addSnapshotSerializer();
ErrorTaskProcessor.addSnapshotSerializer(expect);
addedSerializer = true;
}
const caseConfig = require(testConfig);
Expand Down
2 changes: 1 addition & 1 deletion packages/rspack-test-tools/src/case/stats-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export function createStatsAPICase(
testConfig: string
) {
if (!addedSerializer) {
StatsAPITaskProcessor.addSnapshotSerializer();
StatsAPITaskProcessor.addSnapshotSerializer(expect);
addedSerializer = true;
}
const caseConfig: TStatsAPICaseConfig = require(testConfig);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

const path = require("path");

module.exports = ({ outputDirectory }) =>
module.exports = (env, { outputDirectory }) =>
class Worker {
constructor(url, options = {}) {
expect(url).toBeInstanceOf(URL);
expect(url.origin).toBe("https://test.cases");
expect(url.pathname.startsWith("/path/")).toBe(true);
env.expect(url).toBeInstanceOf(URL);
env.expect(url.origin).toBe("https://test.cases");
env.expect(url.pathname.startsWith("/path/")).toBe(true);
this.url = url;
const file = url.pathname.slice(6);
const workerBootstrap = `
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ module.exports = (globalTimeout = 2000, nameSuffix = "") => {
getNumberOfTests() {
return numberOfTests;
},
expect,
it(...args) {
numberOfTests++;
if (runTests >= numberOfTests) throw new Error("it called too late");
Expand Down
10 changes: 5 additions & 5 deletions packages/rspack-test-tools/src/processor/defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ export class DefaultsConfigTaskProcessor extends SimpleTaskProcessor<ECompilerTy
jestDiff(this.defaultConfig, config, { expand: false, contextLines: 0 })!
);
await this._defaultsConfigOptions.diff(
expect(new Diff(diff)),
expect(this.defaultConfig)
env.expect(new Diff(diff)),
env.expect(this.defaultConfig)
);
}

Expand Down Expand Up @@ -122,8 +122,8 @@ export class DefaultsConfigTaskProcessor extends SimpleTaskProcessor<ECompilerTy
return config;
}

static addSnapshotSerializer() {
expect.addSnapshotSerializer({
static addSnapshotSerializer(expectImpl: jest.Expect) {
expectImpl.addSnapshotSerializer({
test(value) {
return value instanceof Diff;
},
Expand All @@ -132,7 +132,7 @@ export class DefaultsConfigTaskProcessor extends SimpleTaskProcessor<ECompilerTy
}
});

expect.addSnapshotSerializer({
expectImpl.addSnapshotSerializer({
test(value) {
return typeof value === "string";
},
Expand Down
2 changes: 1 addition & 1 deletion packages/rspack-test-tools/src/processor/diagnostic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export class RspackDiagnosticProcessor extends BasicTaskProcessor<ECompilerType.
fs.writeFileSync(errorOutputPath, escapeEOL(output));
} else {
const expectContent = fs.readFileSync(errorOutputPath, "utf-8");
expect(escapeEOL(output)).toBe(escapeEOL(expectContent));
env.expect(escapeEOL(output)).toBe(escapeEOL(expectContent));
}
}

Expand Down
14 changes: 7 additions & 7 deletions packages/rspack-test-tools/src/processor/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,21 +140,21 @@ export class ErrorTaskProcessor<
async check(env: ITestEnv, context: ITestContext) {
const compiler = this.getCompiler(context);
const stats = compiler.getStats();
expect(typeof stats).toBe("object");
env.expect(typeof stats).toBe("object");
const statsResult = stats!.toJson({ errorDetails: false });
expect(typeof statsResult).toBe("object");
env.expect(typeof statsResult).toBe("object");
const { errors, warnings } = statsResult;
expect(Array.isArray(errors)).toBe(true);
expect(Array.isArray(warnings)).toBe(true);
env.expect(Array.isArray(errors)).toBe(true);
env.expect(Array.isArray(warnings)).toBe(true);

await this._errorOptions.check?.({
errors: errors as StatsError[],
warnings: warnings as StatsWarnings[]
});
}

static addSnapshotSerializer() {
expect.addSnapshotSerializer({
static addSnapshotSerializer(expectImpl: jest.Expect) {
expectImpl.addSnapshotSerializer({
test(received) {
return received.errors || received.warnings;
},
Expand All @@ -170,7 +170,7 @@ export class ErrorTaskProcessor<
}
});

expect.addSnapshotSerializer({
expectImpl.addSnapshotSerializer({
test(received) {
return received.message;
},
Expand Down
6 changes: 3 additions & 3 deletions packages/rspack-test-tools/src/processor/hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,14 @@ export class RspackHashProcessor extends MultiTaskProcessor<ECompilerType.Rspack
const testConfig = context.getTestConfig();
const stats = compiler.getStats();
if (!stats) {
expect(false);
env.expect(false);
return;
}
const statsJson = stats.toJson({ assets: true });
if (REG_ERROR_CASE.test(this._options.name)) {
expect((statsJson.errors || []).length > 0);
env.expect((statsJson.errors || []).length > 0);
} else {
expect((statsJson.errors || []).length === 0);
env.expect((statsJson.errors || []).length === 0);
}

if (typeof testConfig.validate === "function") {
Expand Down
13 changes: 6 additions & 7 deletions packages/rspack-test-tools/src/processor/hook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ export class HookCasesContext extends TestContext {
* @internal
*/
async collectSnapshots(
env: ITestEnv,
options = {
diff: {}
}
Expand All @@ -167,12 +168,10 @@ export class HookCasesContext extends TestContext {
group = `# ${group}\n\n`;
return (acc += group + block);
}, "");

// @ts-ignore
expect(snapshots).toMatchFileSnapshot(
path.join(this.src, "hooks.snap.txt"),
options
);
env
.expect(snapshots)
// @ts-ignore
.toMatchFileSnapshot(path.join(this.src, "hooks.snap.txt"), options);
}
}

Expand Down Expand Up @@ -230,7 +229,7 @@ export class HookTaskProcessor extends SnapshotProcessor<ECompilerType.Rspack> {
}

async check(env: ITestEnv, context: HookCasesContext) {
await (context as any).collectSnapshots();
await (context as any).collectSnapshots(env);
await super.check(env, context);
if (typeof this._hookOptions.check === "function") {
await this._hookOptions.check(context);
Expand Down
10 changes: 6 additions & 4 deletions packages/rspack-test-tools/src/processor/hot-step.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export class RspackHotStepProcessor extends RspackHotProcessor {
}
}
this.matchStepSnapshot(
env,
context,
hotUpdateContext.updateIndex,
statsJson,
Expand All @@ -114,7 +115,7 @@ export class RspackHotStepProcessor extends RspackHotProcessor {
const compiler = this.getCompiler(context);
const stats = compiler.getStats();
if (!stats || !stats.hash) {
expect(false);
env.expect(false);
return;
}
const statsJson = stats.toJson({ assets: true, chunks: true });
Expand All @@ -125,7 +126,7 @@ export class RspackHotStepProcessor extends RspackHotProcessor {
}
let matchFailed: Error | null = null;
try {
this.matchStepSnapshot(context, 0, statsJson);
this.matchStepSnapshot(env, context, 0, statsJson);
} catch (e) {
matchFailed = e as Error;
}
Expand All @@ -136,6 +137,7 @@ export class RspackHotStepProcessor extends RspackHotProcessor {
}

protected matchStepSnapshot(
env: ITestEnv,
context: ITestContext,
step: number,
stats: StatsCompilation,
Expand All @@ -145,7 +147,7 @@ export class RspackHotStepProcessor extends RspackHotProcessor {
const compilerOptions = compiler.getOptions();
const getModuleHandler =
GET_MODULE_HANDLER[compilerOptions.target as TSupportTarget];
expect(typeof getModuleHandler).toBe("function");
env.expect(typeof getModuleHandler).toBe("function");

const lastHash = this.hashes[this.hashes.length - 1];
const snapshotPath = context.getSource(
Expand Down Expand Up @@ -359,6 +361,6 @@ ${runtime.javascript.disposedModules.map(i => `- ${i}`).join("\n")}
return;
}
const snapshotContent = escapeEOL(fs.readFileSync(snapshotPath, "utf-8"));
expect(content).toBe(snapshotContent);
env.expect(content).toBe(snapshotContent);
}
}
2 changes: 1 addition & 1 deletion packages/rspack-test-tools/src/processor/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,6 @@ export class SnapshotProcessor<
return;
}
const snapshotContent = escapeEOL(fs.readFileSync(snapshotPath, "utf-8"));
expect(content).toBe(snapshotContent);
env.expect(content).toBe(snapshotContent);
}
}
6 changes: 3 additions & 3 deletions packages/rspack-test-tools/src/processor/stats-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,11 @@ export class StatsAPITaskProcessor<
async check(env: ITestEnv, context: ITestContext) {
const compiler = this.getCompiler(context);
const stats = compiler.getStats();
expect(typeof stats).toBe("object");
env.expect(typeof stats).toBe("object");
await this._statsAPIOptions.check?.(stats!, compiler.getCompiler()!);
}

static addSnapshotSerializer() {
expect.addSnapshotSerializer(serializer);
static addSnapshotSerializer(expectImpl: jest.Expect) {
expectImpl.addSnapshotSerializer(serializer);
}
}
10 changes: 5 additions & 5 deletions packages/rspack-test-tools/src/processor/stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export class RspackStatsProcessor extends MultiTaskProcessor<ECompilerType.Rspac
}

if (REG_ERROR_CASE.test(this._options.name)) {
expect(stats.hasErrors()).toBe(true);
env.expect(stats.hasErrors()).toBe(true);
} else if (stats.hasErrors()) {
throw new Error(
stats.toString({
Expand Down Expand Up @@ -141,14 +141,14 @@ export class RspackStatsProcessor extends MultiTaskProcessor<ECompilerType.Rspac
for (const { compilation: s } of [].concat(
(stats as any).stats || stats
) as Stats[]) {
expect(s.startTime).toBeGreaterThan(0);
expect(s.endTime).toBeGreaterThan(0);
env.expect(s.startTime).toBeGreaterThan(0);
env.expect(s.endTime).toBeGreaterThan(0);
s.endTime = new Date("04/20/1970, 12:42:42 PM").getTime();
s.startTime = s.endTime - 1234;
}

let actual = stats.toString(toStringOptions);
expect(typeof actual).toBe("string");
env.expect(typeof actual).toBe("string");
if (!hasColorSetting) {
actual = this.stderr.toString() + actual;
actual = actual
Expand Down Expand Up @@ -181,7 +181,7 @@ export class RspackStatsProcessor extends MultiTaskProcessor<ECompilerType.Rspac
.replace(/(\w)\\(\w)/g, "$1/$2")
.replace(/, additional resolving: X ms/g, "")
.replace(/Unexpected identifier '.+?'/g, "Unexpected identifier");
expect(actual).toMatchSnapshot();
env.expect(actual).toMatchSnapshot();
const testConfig = context.getTestConfig();
if (typeof testConfig?.validate === "function") {
testConfig.validate(stats, this.stderr.toString());
Expand Down
7 changes: 4 additions & 3 deletions packages/rspack-test-tools/src/runner/runner/cjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ export class CommonJsRunner<
protected createGlobalContext(): IBasicGlobalContext {
return {
console: console,
expect: expect,
setTimeout: ((
cb: (...args: any[]) => void,
ms: number | undefined,
Expand All @@ -39,12 +38,12 @@ export class CommonJsRunner<
protected createBaseModuleScope(): IBasicModuleScope {
const baseModuleScope: IBasicModuleScope = {
console: this.globalContext!.console,
expect: this.globalContext!.expect,
setTimeout: this.globalContext!.setTimeout,
clearTimeout: this.globalContext!.clearTimeout,
it: this._options.env.it,
beforeEach: this._options.env.beforeEach,
afterEach: this._options.env.afterEach,
expect: this._options.env.expect,
jest,
nsObj: (m: Object) => {
Object.defineProperty(m, Symbol.toStringTag, {
Expand All @@ -71,7 +70,9 @@ export class CommonJsRunner<
exports: m.exports,
__dirname: path.dirname(file.path),
__filename: file.path,
_globalAssign: { expect },
_globalAssign: {
expect: this._options.env.expect
},
define
};
}
Expand Down
Loading

2 comments on commit 5fbabcf

@rspack-bot
Copy link

Choose a reason for hiding this comment

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

📝 Ran ecosystem CI: Open

suite result
modernjs, self-hosted, Linux, ci ❌ failure
_selftest, ubuntu-latest ✅ success
nx, ubuntu-latest ✅ success
rspress, ubuntu-latest ✅ success
rsbuild, ubuntu-latest ✅ success
compat, ubuntu-latest ✅ success
examples, ubuntu-latest ❌ failure

@rspack-bot
Copy link

Choose a reason for hiding this comment

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

📝 Benchmark detail: Open

Name Base (2024-05-20 549ab61) Current Change
10000_development-mode + exec 2.59 s ± 19 ms 2.6 s ± 18 ms +0.44 %
10000_development-mode_hmr + exec 703 ms ± 5.7 ms 709 ms ± 8.1 ms +0.80 %
10000_production-mode + exec 2.45 s ± 45 ms 2.49 s ± 36 ms +1.43 %
arco-pro_development-mode + exec 2.48 s ± 51 ms 2.45 s ± 69 ms -0.85 %
arco-pro_development-mode_hmr + exec 432 ms ± 1.7 ms 432 ms ± 2.1 ms -0.03 %
arco-pro_development-mode_hmr_intercept-plugin + exec 442 ms ± 3.4 ms 442 ms ± 1.3 ms +0.07 %
arco-pro_development-mode_intercept-plugin + exec 3.3 s ± 50 ms 3.3 s ± 78 ms 0.00 %
arco-pro_production-mode + exec 4 s ± 87 ms 4 s ± 78 ms 0.00 %
arco-pro_production-mode_intercept-plugin + exec 4.84 s ± 62 ms 4.87 s ± 103 ms +0.63 %
threejs_development-mode_10x + exec 1.97 s ± 23 ms 1.97 s ± 13 ms -0.13 %
threejs_development-mode_10x_hmr + exec 748 ms ± 8.5 ms 762 ms ± 19 ms +1.91 %
threejs_production-mode_10x + exec 5.19 s ± 30 ms 5.19 s ± 35 ms -0.02 %

Please sign in to comment.