如何模拟使用Jest抛出异常的非异步方法?

问题描述 投票:0回答:1

这是我在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);
});

createMyController方法不是同步的,也不是MyService:两者都只是常规方法。现在,当我尝试运行此测试时,它会在抛出异常的模拟方法的行上失败:throw new Error(),只有当我用create包装try/catch方法时,它才能正常工作:

try {
    expect(myController.create(data)).toThrowError(Error);
}
catch { }

这对我来说很奇怪。如果没有在设计中包装try/catch,它不应该工作吗?

javascript testing jestjs ts-jest
1个回答
1
投票

你只需要一个小小的改变。


来自.toThrowError doc

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


您正在传递调用myController.create(data)的结果。

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

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

将您的expect行更改为:

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

......它应该有效。

© www.soinside.com 2019 - 2024. All rights reserved.