【发布时间】:2020-06-22 07:31:17
【问题描述】:
我使用 Mongdoose 和 Nestjs 创建了一个简单的 REST API。我总共进行了 2 次测试,但都失败了。 测试输出:
失败 src/app/auth/auth.service.spec.ts ● 测试套件无法运行
Cannot find module '@shared/errors' from 'auth.service.ts'
5 |
6 | import { AppLogger } from '../logger/logger';
> 7 | import { Errors } from '@shared/errors';
| ^
8 | import { ILoginDto } from './dto/login.dto';
9 | import { ITokenDto } from './dto/auth.dto';
10 | import { IUser } from '@user/document/user.doc';
at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:259:17)
at Object.<anonymous> (auth/auth.service.ts:7:1)
失败 src/app/user/user.service.spec.ts ● 测试套件无法运行
Cannot find module '@shared/errors' from 'user.service.ts'
1 | import { BadRequestException, Injectable } from '@nestjs/common';
2 | import { InjectModel } from '@nestjs/mongoose';
> 3 | import { Errors } from '@shared/errors';
| ^
4 | import { createMultipleRandom } from '@shared/utils';
5 | import { Model } from 'mongoose';
6 | import { AppLogger } from '../logger/logger';
at Resolver.resolveModule (../../node_modules/jest-resolve/build/index.js:259:17)
at Object.<anonymous> (user/user.service.ts:3:1)
测试套件:2 个失败,总共 2 个 测试:共 0 快照:共 0 个 时间:2.751s 运行所有测试套件。
tsconfig.json:
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es2017",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"paths": {
"@app/*": ["src/app/*"],
"@auth/*": ["src/app/auth/*"],
"@config/*": ["config/*"],
"@logger/*": ["src/app/logger/*"],
"@shared/*": ["src/app/shared/*"],
"@user/*": ["src/app/user/*"],
}
},
"include": [
"src/**/*"
],
"exclude": ["node_modules", "dist"]
}
auth.service.spec.ts:
import { Test, TestingModule } from '@nestjs/testing';
import { AuthService } from './auth.service';
describe('AuthService', () => {
let service: AuthService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [AuthService],
}).compile();
service = module.get<AuthService>(AuthService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
});
在@shared/errors.ts 我只是导出一个常量变量。既然它不是一个模块,我应该如何在测试中导入它?我该如何解决这个问题?
【问题讨论】: