我有一个NestJs文件,我试图用Jest编写一些测试,因为我试图在端点上运行一些e2e测试。我的测试文件位于控制器的同一目录级别。我正在尝试测试PlaceController,我的place.controller.spec.ts
文件与PlaceService和PlaceController位于同一目录级别。
spec文件如下所示:
import { Test, TestingModule } from '@nestjs/testing';
import { PlaceController } from './place.controller';
import { PlaceService } from './place.service';
import { expect } from 'chai';
describe('PlaceController', () => {
let appController: PlaceController;
beforeEach(async () => {
const app: TestingModule = await Test.createTestingModule({
controllers: [PlaceController],
providers: [PlaceService],
}).compile();
appController = app.get<PlaceController>(PlaceController);
});
it('should be defined', () => {
expect(appController).toBeDefined();
});
});
我的jest.config.ts看起来像这样:
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['**/**/*.spec.ts'],
verbose: true,
forceExit: true,
clearMocks: true,
resetMocks: true,
restoreMocks: true,
bail: false,
};
我在项目根目录下的tsconfig.json是这样的:
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./src",
"outDir": "./dist",
"incremental": true,
"sourceMap": true,
"declaration": false,
"removeComments": true,
"downlevelIteration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"module": "commonjs",
"moduleResolution": "node",
"importHelpers": true,
"skipLibCheck": true,
"target": "es2017",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2018",
"dom"
],
"paths": {
"@app/*": [
"./client/app/*"
],
"@assets/*": [
"./client/assets/*"
],
"@env/*": [
"./client/environments/*"
],
"@common/*": [
"./common/*"
],
"@server/*": [
"./server/*"
]
}
},
}
我不知道为什么,但是在所有控制器/controller.spec文件所在的目录中有另一个tsconfig文件。这不是我写的所以我不想碰它。但看起来是这样的
{
"extends": "../../tsconfig.json",
"exclude": ["node_modules", "test", "dist"]
}
为了运行测试,我在package.json脚本中有"test": "NODE_ENV=test jest"
。但是,当我运行npm run test
时,我得到了以下错误:
Cannot find module '@server/app/api/place/place.dto' from 'src/server/app/api/place/place.controller.ts'
Require stack:
src/server/app/api/place/place.controller.ts
src/server/app/api/place/place.controller.spec.ts
> 1 | import { CreatePlaceDto } from '@server/app/api/place/place.dto';
| ^
2 | import { PlaceService } from '@server/app/api/place/place.service';
3 | import { CrudRequest } from '@server/app/core/crud/crud';
4 | import {
但是当我正常运行应用程序时,而不是测试,一切都运行得很完美,当我在Postman中调用它时,我的API返回正确的响应。是什么导致了这个问题?谢谢你!
1条答案
按热度按时间0aydgbwb1#
如果直接用'./'而不是src显示路径,问题就解决了。