【发布时间】:2019-07-31 07:33:28
【问题描述】:
这是我在 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);
});
MyController 的create 方法不是异步的,MyService 也不是:两者都只是常规方法。现在,当我尝试运行此测试时,它在引发异常的模拟方法的行上失败:throw new Error() 并且只有当我将 create 方法调用与 try/catch 包装在一起时它才能正常工作:
try {
expect(myController.create(data)).toThrowError(Error);
}
catch { }
我觉得这很奇怪。如果不按设计包装在 try/catch 中,它不应该工作吗?
【问题讨论】:
标签: javascript testing jestjs ts-jest