gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:18:18 25 4
gpt4 key购买 nike

这是我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com