Node.js 如何在NestJS中模拟存储库、服务和控制器(Typeorm&;Jest)
我是打字新手。我的Nestjs项目应用程序是这样的。我试图使用存储库模式,所以我将业务逻辑(服务)和持久性逻辑(存储库)分开 UserRepositoryNode.js 如何在NestJS中模拟存储库、服务和控制器(Typeorm&;Jest),node.js,typescript,jestjs,nestjs,typeorm,Node.js,Typescript,Jestjs,Nestjs,Typeorm,我是打字新手。我的Nestjs项目应用程序是这样的。我试图使用存储库模式,所以我将业务逻辑(服务)和持久性逻辑(存储库)分开 UserRepository import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { UserEntity } from './entiti
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { UserEntity } from './entities/user.entity';
@Injectable()
export class UserRepo {
constructor(@InjectRepository(UserEntity) private readonly repo: Repository<UserEntity>) {}
public find(): Promise<UserEntity[]> {
return this.repo.find();
}
}
UserController
如何为存储库、服务和控制器创建单元测试,而不实际将数据持久化或检索到数据库(使用mock)?使用测试工具Nest exposes is
@NestJS/testing
可以很容易地在NestJS中进行mock。简言之,您需要为希望模拟的依赖项创建一个模型,这就是全部内容。但是,最好看一个例子,因此这里有一个控制器模拟的可能性:
description('UserController',()=>{
let控制器:UserController;
let服务:UserService;
beforeach(异步()=>{
const moduleRef=await Test.createTestingModule({
控制器:[UserController],
供应商:[
{
提供:用户服务,
使用价值:{
get:jest.fn(()=>mockUserEntity)//实际上它可以是任何东西,但越接近实际逻辑越好
}
}
]
}).compile();
controller=moduleRef.get(UserController);
service=moduleRef.get(UserService);
});
});
从那里你可以继续写你的测试。对于使用Nest的DI系统的所有测试,这几乎是相同的设置,唯一需要注意的是
@InjectRepository()
和@InjectModel()
(Mongoose和Sequilize decorators),其中您需要为注入令牌使用getRepositoryToken()
或getModelToken()
。如果您正在寻找更多Exmaple,请提供一个完整的示例?我希望实现同样的目标。我的答案中链接的存储库中有完整的示例,您可以查看@p0ttaI,我以前没有在正确的位置查找。现在找到了,谢谢!
import { Injectable } from '@nestjs/common';
import { UserRepo } from './user.repository';
@Injectable()
export class UserService {
constructor(private readonly userRepo: UserRepo) {}
public async get() {
return this.userRepo.find();
}
}
import { Controller, Get } from '@nestjs/common';
import { UserService } from './user.service';
@Controller('/users')
export class UserController {
constructor(private readonly userService: UserService) {}
// others method //
@Get()
public async getUsers() {
try {
const payload = this.userService.get();
return this.Ok(payload);
} catch (err) {
return this.InternalServerError(err);
}
}
}