admin管理员组文章数量:1356142
I want to run some stuff only once before all test cases. Therefore, I have created a global function and specified the globalSetup field in the jest configuration:
globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
However, within globalSetup, I use some aliases @ and Jest plains it does not find them.
How can I run globalSetup once the aliases have been sorted out?
My Jest configuration is as follows:
module.exports = {
rootDir: rootPath,
coveragePathIgnorePatterns: ['/node_modules/'],
preset: 'ts-jest',
setupFiles: [path.resolve(__dirname, 'env.testing.ts')],
setupFilesAfterEnv: [path.resolve(srcPath, 'TestUtils', 'testSetup.ts')],
globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
globals: {},
testEnvironment: 'node',
moduleFileExtensions: ['js', 'ts', 'json'],
moduleNameMapper: pathsToModuleNameMapper(pilerOptions.paths, { prefix: '<rootDir>/' })
};
When I run testSetup before every test, it runs ok the aliases, but this does not happen with globalSetup.
Any clue what could I do?
I want to run some stuff only once before all test cases. Therefore, I have created a global function and specified the globalSetup field in the jest configuration:
globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
However, within globalSetup, I use some aliases @ and Jest plains it does not find them.
How can I run globalSetup once the aliases have been sorted out?
My Jest configuration is as follows:
module.exports = {
rootDir: rootPath,
coveragePathIgnorePatterns: ['/node_modules/'],
preset: 'ts-jest',
setupFiles: [path.resolve(__dirname, 'env.testing.ts')],
setupFilesAfterEnv: [path.resolve(srcPath, 'TestUtils', 'testSetup.ts')],
globalSetup: path.resolve(srcPath, 'TestUtils', 'globalSetup.ts'),
globals: {},
testEnvironment: 'node',
moduleFileExtensions: ['js', 'ts', 'json'],
moduleNameMapper: pathsToModuleNameMapper(pilerOptions.paths, { prefix: '<rootDir>/' })
};
When I run testSetup before every test, it runs ok the aliases, but this does not happen with globalSetup.
Any clue what could I do?
Share Improve this question edited Dec 28, 2020 at 9:19 jonrsharpe 122k30 gold badges268 silver badges475 bronze badges asked Dec 28, 2020 at 9:10 Javier GuzmánJavier Guzmán 1,2034 gold badges16 silver badges33 bronze badges 1- Please give a minimal reproducible example including the relevant code and error messages. – jonrsharpe Commented Dec 28, 2020 at 9:22
3 Answers
Reset to default 9I managed to get this work by including tsconfig-paths/register
at the top of my globalSetup file:
// myGlobalSetupFile.ts
import 'tsconfig-paths/register';
import { Thing } from './place-with-aliases';
export default async () => {
await Thing.doGlobalSetup();
}
You have to make sure you have tsconfig-paths
installed in your project.
Unfortunately I have found there is no solution for this based on the ments on this issue: https://github./facebook/jest/issues/6048
The summary is that globalSetup runs outside of Jest ecosystem and therefore it will not recognize the aliases, etc.
There are several workarounds, for example, if your npm run test mand is something like this:
"test": "jest --config config/jest.config.js --detectOpenHandles --forceExit"
Then you can do something like:
"test": "node whateverBeforeJest.js && jest --config config/jest.config.js --detectOpenHandles --forceExit"
Javier is right that globalSetup runs outside of the Jest ecosystem and will not recognize the aliases.
But I solved the problem this way:
Folder Structure:
src
└── __tests__
└── client
└── server
└── tsconfig.json
└── _config
└── jest.config.ts
└── jest.global.setup.ts
└── jest.global.teardown.ts
└── controllers
└── public.test.ts
└── ...more
└── client
└── ...more
└── server
└── controllers
└── ...more
└── tsconfig-base.json
package.json
package.json
{
...
"dependencies": {
...
},
"devDependencies": {
"supertest": "^6.3.4",
"ts-jest": "^29.1.2",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.4.2",
...
},
"_moduleAliases": {
"@/controllers": "bin/controllers",
"@/enums": "bin/enums",
"@/exceptions": "bin/exceptions",
"@/interfaces": "bin/interfaces"
},
...
}
tsconfig-base.json
{
"pilerOptions": {
"target": "es2020",
"types": ["node", "jest"],
"posite": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"sourceMap": true,
"strict": true,
"alwaysStrict": true,
"noImplicitAny": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"esModuleInterop": true,
"removeComments": true,
//"traceResolution": true,
},
"include": [
],
"exclude": [
"**/node_modules/*",
"bin",
"public"
]
}
{
"extends": "../../tsconfig-base.json",
"pilerOptions": {
"module": "NodeNext",
"baseUrl": ".",
"rootDir": "../..",
"outDir": "../../../bintests",
"paths": {
"@/controllers/*": ["../../server/controllers/*"],
"@/enums/*": ["../../server/enums/*"],
"@/exceptions/*": ["../../server/exceptions/*"],
"@/interfaces/*": ["../../server/interfaces/*"]
},
},
"include": [
"**/next-env.d.ts",
"**/*.ts",
"../../server/**/*.ts"
],
"exclude": [
"**/node_modules/*",
"bin",
"public"
]
}
jest.config.ts
import _path from 'path';
import type { Config } from '@jest/types';
import { pathsToModuleNameMapper } from 'ts-jest';
const testsSrc: string = _path.resolve(__dirname, '../..');
const serverSrc: string = _path.resolve(__dirname, '../../../server');
export const aliases: any = {
'@/controllers/*': [`${serverSrc}/controllers/*`],
'@/enums/*': [`${serverSrc}/enums/*`],
'@/exceptions/*': [`${serverSrc}/exceptions/*`],
'@/interfaces/*': [`${serverSrc}/interfaces/*`],
};
const config: Config.InitialOptions = {
rootDir: `${testsSrc}/server`,
roots: ['<rootDir>'],
testMatch: [
//'**/__tests__/**/*.+(ts|tsx|js)',
'**/?(*.)+(spec|test).+(ts|tsx|js)',
],
transform: {
'^.+\\.(ts|tsx)$': 'ts-jest',
},
preset: 'ts-jest',
//'ts-jest/presets/default-esm',
testEnvironment: 'node',
verbose: true,
automock: false,
globalSetup: '<rootDir>/_config/jest.global.setup.ts',
globalTeardown: '<rootDir>/_config/jest.global.teardown.ts',
modulePaths: [serverSrc], // <-- This will be set to 'baseUrl' value
moduleNameMapper: pathsToModuleNameMapper(aliases /* ,{ prefix: '<rootDir>/' } */),
};
export default config;
jest.global.setup.ts
import _path from 'path';
import * as TSConfigPaths from 'tsconfig-paths';
import { aliases } from './jest.config';
const baseUrl: string = _path.resolve(__dirname, '..');
// @ts-ignore: TS6133
const cleanup: () => void = TSConfigPaths.register({
baseUrl,
paths: aliases, // tsConfig.pilerOptions.paths,
});
import ExpressApp from '@/controllers/express-server';
import PublicController from '@/controllers/public';
export const globalSetup: () => Promise<void>
= async (): Promise<void> => {
const expressApp: ExpressApp | null = new ExpressApp();
expressApp?.initializeControllers([
new PublicController(expressApp),
]);
(globalThis as any).__ExpressApp__ = expressApp;
};
// afterAll(async (): Promise<void> => {
// });
export default globalSetup;
And finally, public.test.ts
import request from 'supertest';
import express from 'express';
import { StatusCodes } from 'http-status-codes';
import ExpressApp from '@/controllers/express-server';
describe('public.test.ts', () => {
//let agent: request.Agent;
//let tmp: any = null;
beforeAll(async (): Promise<void> => {
ExpressApp.me = (globalThis as any).__ExpressApp__;
//agent = request.agent(ExpressApp.me?.app || undefined);
});
test('get /public/v1/version', async (): Promise<void> => {
const expressApp: ExpressApp | null = ExpressApp.me;
const response: any = await request(expressApp?.app as express.Application)
.get('/public/v1/version');
expect(response.statusCode).toBe(StatusCodes.OK);
expect(response.body).toBe('1.0.0.0');
});
});
本文标签: javascriptHow to find aliases in Global Jest setupStack Overflow
版权声明:本文标题:javascript - How to find aliases in Global Jest setup? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744000152a2573711.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论