这是我在 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
中,它不应该工作吗?通过设计?
最佳答案
你只需要一点零钱。
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/