如何模拟非异步方法以用Jest引发异常?

时间:2019-03-09 12:16:10

标签: testing jestjs ts-jest

这是我在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 { } 中,是否可以正常工作?

1 个答案:

答案 0 :(得分:1)

您只需要一点零钱。


来自.toThrowError doc

  

使用.toThrowError测试函数在调用时是否抛出。


您正在传递呼叫结果 myController.create(data)

您需要传递在调用时会抛出的函数,在这种情况下:

() => { myController.create(data); }

将您的expect行更改为此:

expect(() => { myController.create(data); }).toThrowError(Error);  // SUCCESS

...它应该可以工作。