ale*_*dro 3 javascript unit-testing node.js jestjs nestjs
我正在寻找一种用 Jest测试我的NestJs PlayerController 的方法。我的控制器和服务声明:
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) { }
Run Code Online (Sandbox Code Playgroud)
我的测试:
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();
});
...
Run Code Online (Sandbox Code Playgroud)
Nest 无法解析 PlayerService(?、CommandBus、EventBus)的依赖关系。请确保索引 [0] 处的参数在 PlayerService 上下文中可用。
Run Code Online (Sandbox Code Playgroud)at Injector.lookupComponentInExports (../node_modules/@nestjs/core/injector/injector.js:180:19)
有什么办法可以解决这个依赖性问题吗?
它不起作用,因为您正在导入PlayerService. 您只能导入模块,提供程序可以通过模块导入或在providers数组中声明:
imports: [PlayerService, CqrsModule]
^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)
但是,在单元测试中,您希望单独测试单个单元,而不是不同单元及其依赖项之间的交互。因此,比导入或声明依赖项更好的方法是为 .xPlayerService或 .x 的提供者提供模拟CqrsModule。
请参阅此答案以了解单元测试和 e2e 测试之间的区别。
有关如何创建模拟的信息,请参阅此答案。
| 归档时间: |
|
| 查看次数: |
8046 次 |
| 最近记录: |