【发布时间】:2019-07-27 08:02:21
【问题描述】:
尝试进行单元测试。 出现以下错误:
TypeError: 无法读取未定义的属性“原型”
导出类 UserService {
constructor(@InjectRepository(User) 私有只读 userRepository: 存储库 ) { }
spec.ts:
describe('AuthController', () => {
let authController: AuthController;
let authService: AuthService;
let mockRepository = {
};
beforeEach(async () => {
const module = await Test.createTestingModule({
imports: [
TypeOrmModule.forFeature([User]),
],
controllers: [AuthController],
providers: [AuthService, {
provide: getRepositoryToken(User),
useValue: mockRepository
}]
}).compile()
authService = module.get<AuthService>(AuthService);
authController = module.get<AuthController>(AuthController)
});
有人可以分享解决方案吗?
更多信息:
所以typeorm 似乎有问题
beforeEach(async () => {
const module = await Test.createTestingModule({
}).compile()
authService = module.get<AuthService>(AuthService);
authController = module.get<AuthController>(AuthController)
});
使用此代码,我得到了完全相同的错误。所以唯一的问题是在这个测试模块中添加typeorm。
所以它因为依赖而失败:AuthController->AuthService->UserService->TypeORM
顺便说一句,刚刚使用带有 Postman 的 API 检查了UserService,它工作正常。
还是没有结果:
module = await Test.createTestingModule({
controllers: [AuthController],
components: [
{
provide: AuthService,
useValue: {}
},
{
provide: UserService,
useValue: {}
},
{
provide: getRepositoryToken(User),
useValue: {}
}
],
providers: [
{
provide: AuthService,
useValue: {}
},
{
provide: UserService,
useValue: {}
},
{
provide: getRepositoryToken(User),
useValue: {}
}
]
}).compile()
this.authController = module.get<AuthController>(AuthController)
还有
class AuthServiceMock {
logIn(userName) {
return { id:100, isDeleted:false, login:"login", password:"password"};
}
signUp() {
return { expireIn: 3600, token:"token" };
}
}
describe('AuthController', () => {
let module: TestingModule;
let authController: AuthController;
let authService: AuthService;
beforeEach(async () => {
module = await Test.createTestingModule({
controllers: [AuthController],
components: [
],
providers: [
{
provide: AuthService,
useClass: AuthServiceMock
},
]
}).compile()
this.authController = module.get<AuthController>(AuthController)
});
【问题讨论】:
-
你解决了吗?我有同样的问题
-
@alex88 是的。我重新创建了项目并将所有旧文件复制到新文件。似乎是一些 typeorm 错误。
标签: typescript jestjs nestjs typeorm