这是我在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
的{{1}}方法不是异步的,MyController
的方法也不是:两者都是常规方法。现在,当我尝试运行此测试时,它在抛出异常的模拟方法的行上失败:MyService
,并且只有当我用throw new Error()
包装create
方法调用时,它才能正常工作像这样:
try/catch
我觉得这很奇怪。如果不按设计将其包装在try {
expect(myController.create(data)).toThrowError(Error);
}
catch { }
中,是否可以正常工作?
答案 0 :(得分:1)
您只需要一点零钱。
使用
.toThrowError
测试函数在调用时是否抛出。
您正在传递呼叫结果 myController.create(data)
。
您需要传递在调用时会抛出的函数,在这种情况下:
() => { myController.create(data); }
将您的expect
行更改为此:
expect(() => { myController.create(data); }).toThrowError(Error); // SUCCESS
...它应该可以工作。