这是我在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
测试函数在调用时是否抛出。
您正在传递调用myController.create(data)
的结果。
在这种情况下,您需要传递一个在调用时抛出的函数:
() => { myController.create(data); }
将您的expect
行更改为:
expect(() => { myController.create(data); }).toThrowError(Error); // SUCCESS
......它应该有效。