javascript - 如何模拟非异步方法以使用 Jest 抛出异常?

标签 javascript testing jestjs ts-jest

这是我在 TypeScript 中的代码片段:

let myService: MyService;
let myController: MyController;

beforeAll(async function () {
    myService = new MyService(null);
    myController = new MyController(myService);
});

it("should fail due to any 'MyService' error", () => {
    jest.spyOn(myService, 'create').mockImplementation(() => {
        throw new Error(); // ! the test fails here
    });
    expect(myController.create(data)).toThrowError(Error);
});

create MyController的方法| 不是异步MyService 也不是: 两者都只是常规方法。现在,当我尝试运行此测试时,它在抛出异常的模拟方法行失败:throw new Error()只有当我包装 create 时它才能正常工作用 try/catch 调用方法像这样:

try {
    expect(myController.create(data)).toThrowError(Error);
}
catch { }

我觉得很奇怪。如果不包装在 try/catch 中,它不应该工作吗?通过设计?

最佳答案

你只需要一点零钱。


来自.toThrowError doc :

Use .toThrowError to test that a function throws when it is called.


您正在传递调用 myController.create(data) 的结果。

您需要传递一个在调用时抛出的函数,在这种情况下:

() => { myController.create(data); }

将您的 expect 行更改为:

expect(() => { myController.create(data); }).toThrowError(Error);  // SUCCESS

...它应该可以工作。

关于javascript - 如何模拟非异步方法以使用 Jest 抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55077255/

相关文章:

testing - 什么是 "0E-20"

typescript - 如何在 NestJS 中对 TypeORM 的自定义存储库进行单元测试?

reactjs - 测试套装因 "SyntaxError: Unexpected token ' export"' react typescript using jest 而失败

javascript - 使用jquery或任何方式获取div内容(javascript代码)

javascript - 在数组中循环数组

javascript - 更改 OpenCV.js 中的像素值

javascript - 为什么删除sessionStorage后仍然存在

testing - Testcafe:您要切换到的 iframe 内容未加载

c# - 使用 Moq 验证方法调用

node.js - 如何在测试中获取 serverless.yml 中定义的环境变量