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

How to mock non-async method for throwing an exception with 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);
});

MyController create 方法不是异步 MyService 也不是:两者都只是常规方法。现在,当我尝试 运行 这个测试时,它在抛出异常的模拟方法行失败:throw new Error() 并且只有当我用 create 方法调用包装时它才能正常工作=17=] 像这样:

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

我觉得很奇怪。如果不按设计包装在 try/catch 中,它不应该工作吗?

你只需要一点零钱。


来自.toThrowError doc

Use .toThrowError to test that a function throws when it is called.


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

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

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

将您的 expect 行更改为:

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

...它应该可以工作。