【发布时间】:2019-08-04 05:21:30
【问题描述】:
我正在使用 NestJS 的 mongoose 模块,所以我有我的架构和接口,在我的服务中我使用 @InjectModel 来注入我的模型。我不知道如何模拟模型以注入我的服务。
我的服务如下所示:
@Injectable()
export class AuthenticationService {
constructor(@InjectModel('User') private readonly userModel: Model<User>) {}
async createUser(dto: CreateUserDto): Promise<User> {
const model = new this.userModel(dto);
model.activationToken = this.buildActivationToken();
return await model.save();
}
}
在我的服务测试中,我有这个:
const mockMongooseTokens = [
{
provide: getModelToken('User'),
useValue: {},
},
];
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
...mockMongooseTokens,
AuthenticationService,
],
}).compile();
service = module.get<AuthenticationService>(AuthenticationService);
});
但是当我运行测试时,我得到了这个错误:
TypeError: this.userModel is not a constructor
我还想让我的模型对其执行单元测试,如article所示
【问题讨论】:
-
我在这里找到了 Kim Kern 的解决方案:stackoverflow.com/questions/55366037/…
标签: nestjs