Skip to content
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

fix: output error when running test in jest environment #2643

Merged
merged 1 commit into from Jan 11, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
190 changes: 99 additions & 91 deletions packages/mock/src/creator.ts
Expand Up @@ -57,112 +57,120 @@ export async function create<
debug(`[mock]: Create app, appDir="${appDir}"`);
process.env.MIDWAY_TS_MODE = 'true';

if (appDir) {
// 处理测试的 fixtures
if (!isAbsolute(appDir)) {
appDir = join(process.cwd(), 'test', 'fixtures', appDir);
}
try {
if (appDir) {
// 处理测试的 fixtures
if (!isAbsolute(appDir)) {
appDir = join(process.cwd(), 'test', 'fixtures', appDir);
}

if (!existsSync(appDir)) {
throw new MidwayCommonError(
`Path "${appDir}" not exists, please check it.`
);
if (!existsSync(appDir)) {
throw new MidwayCommonError(
`Path "${appDir}" not exists, please check it.`
);
}
}
}

clearAllLoggers();
clearAllLoggers();

options = options || ({} as any);
if (options.baseDir) {
safeRequire(join(`${options.baseDir}`, 'interface'));
} else if (appDir) {
options.baseDir = `${appDir}/src`;
safeRequire(join(`${options.baseDir}`, 'interface'));
}
options = options || ({} as any);
if (options.baseDir) {
safeRequire(join(`${options.baseDir}`, 'interface'));
} else if (appDir) {
options.baseDir = `${appDir}/src`;
safeRequire(join(`${options.baseDir}`, 'interface'));
}

if (options.entryFile) {
// start from entry file, like bootstrap.js
options.entryFile = formatPath(appDir, options.entryFile);
global['MIDWAY_BOOTSTRAP_APP_READY'] = false;
// set app in @midwayjs/bootstrap
require(options.entryFile);

await new Promise<void>((resolve, reject) => {
const timeoutHandler = setTimeout(() => {
clearInterval(internalHandler);
reject(new Error('[midway]: bootstrap timeout'));
}, options.bootstrapTimeout || 30 * 1000);
const internalHandler = setInterval(() => {
if (global['MIDWAY_BOOTSTRAP_APP_READY'] === true) {
clearInterval(internalHandler);
clearTimeout(timeoutHandler);
resolve();
} else {
debug('[mock]: bootstrap not ready and wait next check');
}
}, 200);
});
return;
}
if (options.entryFile) {
// start from entry file, like bootstrap.js
options.entryFile = formatPath(appDir, options.entryFile);
global['MIDWAY_BOOTSTRAP_APP_READY'] = false;
// set app in @midwayjs/bootstrap
require(options.entryFile);

if (!options.imports && customFramework) {
options.imports = transformFrameworkToConfiguration(customFramework);
}
await new Promise<void>((resolve, reject) => {
const timeoutHandler = setTimeout(() => {
clearInterval(internalHandler);
reject(new Error('[midway]: bootstrap timeout'));
}, options.bootstrapTimeout || 30 * 1000);
const internalHandler = setInterval(() => {
if (global['MIDWAY_BOOTSTRAP_APP_READY'] === true) {
clearInterval(internalHandler);
clearTimeout(timeoutHandler);
resolve();
} else {
debug('[mock]: bootstrap not ready and wait next check');
}
}, 200);
});
return;
}

if (customFramework?.['Configuration']) {
options.imports = customFramework;
customFramework = customFramework['Framework'];
}
if (!options.imports && customFramework) {
options.imports = transformFrameworkToConfiguration(customFramework);
}

const container = new MidwayContainer();
const bindModuleMap: WeakMap<any, boolean> = new WeakMap();
// 这里设置是因为在 midway 单测中会不断的复用装饰器元信息,又不能清理缓存,所以在这里做一些过滤
container.onBeforeBind(target => {
bindModuleMap.set(target, true);
});
if (customFramework?.['Configuration']) {
options.imports = customFramework;
customFramework = customFramework['Framework'];
}

const originMethod = container.listModule;
const container = new MidwayContainer();
const bindModuleMap: WeakMap<any, boolean> = new WeakMap();
// 这里设置是因为在 midway 单测中会不断的复用装饰器元信息,又不能清理缓存,所以在这里做一些过滤
container.onBeforeBind(target => {
bindModuleMap.set(target, true);
});

container.listModule = key => {
const modules = originMethod.call(container, key);
if (key === CONFIGURATION_KEY) {
return modules;
}
const originMethod = container.listModule;

return modules.filter((module: any) => {
if (bindModuleMap.has(module)) {
return true;
} else {
debug(
'[mock] Filter "%o" module without binding when list module %s.',
module.name ?? module,
key
);
return false;
container.listModule = key => {
const modules = originMethod.call(container, key);
if (key === CONFIGURATION_KEY) {
return modules;
}
});
};

options.applicationContext = container;
return modules.filter((module: any) => {
if (bindModuleMap.has(module)) {
return true;
} else {
debug(
'[mock] Filter "%o" module without binding when list module %s.',
module.name ?? module,
key
);
return false;
}
});
};

await initializeGlobalApplicationContext({
...options,
appDir,
asyncContextManager: createContextManager(),
imports: []
.concat(options.imports)
.concat(
options.baseDir
? safeRequire(join(options.baseDir, 'configuration'))
: []
),
});
options.applicationContext = container;

await initializeGlobalApplicationContext({
...options,
appDir,
asyncContextManager: createContextManager(),
imports: []
.concat(options.imports)
.concat(
options.baseDir
? safeRequire(join(options.baseDir, 'configuration'))
: []
),
});

if (customFramework) {
return container.getAsync(customFramework as any);
} else {
const frameworkService = await container.getAsync(MidwayFrameworkService);
return frameworkService.getMainFramework() as T;
if (customFramework) {
return container.getAsync(customFramework as any);
} else {
const frameworkService = await container.getAsync(MidwayFrameworkService);
return frameworkService.getMainFramework() as T;
}
} catch (err) {
// catch for jest beforeAll can't throw error
if (process.env.JEST_WORKER_ID) {
console.error(err);
}
throw err;
}
}

Expand Down