我刚开始打字。我的Nestjs项目应用程序就是这样的。我试图使用存储库模式,所以我将业务逻辑(服务)和持久逻辑(存储库)分开
UserRepository
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();
}
}
UserService
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();
}
}
UserController
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);
}
}
}
如何为存储库、服务和控制器创建单元测试,而不实际将数据持久化或检索到DB (使用模拟)?
发布于 2020-03-12 15:28:15
使用Nest公开的测试工具Nest可以很容易地获得NestJS中的模拟是@nestjs/testing
。简而言之,您需要为所要模拟的依赖项创建一个自定义提供程序,仅此而已。然而,看一个示例总是更好的,因此这里有一种控制器模拟的可能性:
describe('UserController', () => {
let controller: UserController;
let service: UserService;
beforeEach(async () => {
const moduleRef = await Test.createTestingModule({
controllers: [UserController],
providers: [
{
provide: UserService,
useValue: {
get: jest.fn(() => mockUserEntity) // really it can be anything, but the closer to your actual logic the better
}
}
]
}).compile();
controller = moduleRef.get(UserController);
service = moduleRef.get(UserService);
});
});
从那里你可以继续写你的测试。对于使用Nest的DI系统的所有测试,这几乎都是相同的设置,唯一需要注意的是@InjectRepository()
和@InjectModel()
(Mongoose和Sequilize装饰器),您将需要使用getRepositoryToken()
或getModelToken()
作为注入令牌。如果你在寻找更多的看看这个存储库
https://stackoverflow.com/questions/60652617
复制相似问题