【问题标题】:Jest Mock Service argument is not assignableJest Mock Service 参数不可分配
【发布时间】:2020-11-01 07:38:04
【问题描述】:

我的 NestJs 应用程序中有一个简单的控制器。

@Post('/')
async create(@Body() createUserRequest: CreateUserRequest): Promise<User> {
  return await this.userService.create(createUserRequest);
}

我的目标是使用 jest 来测试这个功能。如您所见,控制器注入了UserService 的实例。所以我尝试在我的单元测试中模拟这个服务。测试用例如下所示。

describe('User Controller', () => {
  let userService: UserService;
  let userController: UserController;

  beforeEach(async () => {
    const module = await Test.createTestingModule({
      controllers: [UserController],
      providers: [UserService],
    }).compile();

    userService = module.get<UserService>(UserService);
    userController = module.get<UserController>(UserController);
  });

  describe('create', () => {
    it('should return a user', async () => {
      const result = new User();

      jest.spyOn(userService, 'create').mockImplementation(() => result);

      expect(await userController.create(new CreateUserRequest())).toBe(result);
    });
  });
});

我的问题是发生模拟的jest.spyOn 会产生错误。

No overload matches this call.
Overload 1 of 4, '(object: UserService, method: never): SpyInstance<never, never>', gave the following error.
Argument of type '"create"' is not assignable to parameter of type 'never'.
Overload 2 of 4, '(object: UserService, method: never): SpyInstance<never, never>', gave the following error.
Argument of type '"create"' is not assignable to parameter of type 'never'.

有人知道我的模拟有什么问题吗?我从documentation 中采用了这种方法。

【问题讨论】:

  • 您的UserService 是否依赖于任何其他依赖项?
  • 是的,它取决于存储库
  • 嗯,nest 无法创建服务,因为它需要存储库。由于无法创建它,因此将其设置为undefined。因为它是未定义的,所以开玩笑不能窥探它
  • 我认为情况并非如此,因为提供了覆盖用户服务中的功能的模拟实现。请参阅 Jest 文档中的 spyOn 文档。

标签: typescript unit-testing jestjs nestjs


【解决方案1】:

这可能不是您期望的响应,但是,您可以实现以下相同的结果:

// ...
describe('create', () => {
  it('should return a user', async () => {
    const result = new User();

    ((userService as unknown) as any).create = jest.fn().mockResolvedValue(result);
    // Or to ensure that the value is only called once, 
    // go ahead and use 'mockResolvedValueOnce'

    expect(await userController.create(new CreateUserRequest())).toBe(result);
  });
});
// ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-12
    • 2020-06-02
    • 2021-06-04
    • 2020-02-25
    • 2021-10-11
    • 2019-06-21
    • 2020-04-02
    • 2022-12-02
    相关资源
    最近更新 更多