【问题标题】:Jest test case is failing in nestjs笑话测试用例在nestjs中失败
【发布时间】:2022-02-11 14:34:57
【问题描述】:

我在服务类的nestjs中有以下方法。

async findOne(id: string): Promise<Certificate> {
    const result = await this.certificateRepository.findOne({ id });
    if (!result) {
        throw new NotFoundException(`Certificate with ID does not exist`);
    }
    return result;
}

我在下面的测试用例中写过同样的内容。

it('should find one certificate', async () => {
        const id = '1';
        const certificate = await service.findOne(id);
        expect(repository.findOne).toHaveBeenCalledTimes(1);
        expect(repository.findOne).toHaveBeenCalledWith(id);
        expect(certificate).toBeInstanceOf(Certificate);
    });

我也遇到了同样的错误。

我不确定它为什么返回 object 而不是 value。如果我不能修改方法,我可以修改这个测试用例来返回object吗?

我应该对我的测试用例进行哪些更改?

【问题讨论】:

  • 错误告诉你什么?你看看const result = await this.certificateRepository.findOne({ id });id 是直接传递给该方法还是作为对象中的属性id?如果你把它改成 `expect(repository.findOne).toHaveBeenCalledWith({ id, "1" });`
  • 我作为财产传递。方法我无权修改。我可以在测试用例中做一些事情以使其成功吗?
  • 不允许更改什么?测试断言?查看代码时断言是错误的。它永远不会以当前状态传递。
  • 哇..它成功了..非常感谢亚历山大。我之前没有阅读完整的评论。你救了我。非常感谢。

标签: javascript node.js unit-testing jestjs nestjs


【解决方案1】:

将断言更新为:

expect(repository.findOne).toHaveBeenCalledWith({ id: "1" });

这将匹配代码使用id 调用certificateRepository.findOne 的方式。

【讨论】:

    猜你喜欢
    • 2017-12-16
    • 2019-07-06
    • 2021-09-13
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 2020-07-12
    • 2021-04-07
    • 1970-01-01
    相关资源
    最近更新 更多