我正在寻找一种方法来使用 Jest 测试我的 NestJs PlayerController。 我的 Controller 和服务声明:
import { QueryBus, CommandBus, EventBus } from '@nestjs/cqrs';
/**
* The service assigned to query the database by means of commands
*/
@Injectable()
export class PlayerService {
/**
* Ctor
* @param queryBus
*/
constructor(
private readonly queryBus: QueryBus,
private readonly commandBus: CommandBus,
private readonly eventBus: EventBus
) { }
@Controller('player')
@ApiUseTags('player')
export class PlayerController {
/**
* Ctor
* @param playerService
*/
constructor(private readonly playerService: PlayerService) { }
我的测试:
describe('Player Controller', () => {
let controller: PlayerController;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
imports: [PlayerService, CqrsModule],
controllers: [PlayerController],
providers: [
PlayerService,
],
}).compile();
controller = module.get<PlayerController>(PlayerController);
});
it('should be defined', () => {
expect(controller).toBeDefined();
});
...
Nest can't resolve dependencies of the PlayerService (?, CommandBus, EventBus). Please make sure that the argument at index [0] is available in the PlayerService context.
at Injector.lookupComponentInExports (../node_modules/@nestjs/core/injector/injector.js:180:19)
有什么方法可以解决这个依赖问题?
最佳答案
它不起作用,因为您正在导入 PlayerService
。您只能导入模块,提供者可以通过模块导入或在 providers
数组中声明:
imports: [PlayerService, CqrsModule]
^^^^^^^^^^^^^
但是,在单元测试中,您希望单独测试单个单元,而不是不同单元及其依赖项之间的交互。为 PlayerService
或 CqrsModule
的提供者提供模拟比导入或声明您的依赖项更好。
参见 this answer区分单元测试和端到端测试。
参见 this answer关于如何创建模拟。
关于javascript - 用 Jest 测试 NestJs 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55567053/