如何正确地使模拟抛出一个错误在开玩笑?

我正在使用 Jest 测试我的 GraphQL api。

我为每个查询/变异使用一个单独的测试套件

我有2个测试(每一个在一个单独的测试套件) ,其中我模拟一个功能(即,流星的 callMethod) ,是用于突变。

  it('should throw error if email not found', async () => {
callMethod
.mockReturnValue(new Error('User not found [403]'))
.mockName('callMethod');


const query = FORGOT_PASSWORD_MUTATION;
const params = { email: 'user@example.com' };


const result = await simulateQuery({ query, params });


console.log(result);


// test logic
expect(callMethod).toBeCalledWith({}, 'forgotPassword', {
email: 'user@example.com',
});


// test resolvers
});

当我 console.log(result)我得到

{ data: { forgotPassword: true } }

这种行为不是我想要的,因为在 .mockReturnValue中我抛出了一个 Error,因此期望 result有一个错误对象

但是,在此测试之前,将运行另一个测试

 it('should throw an error if wrong credentials were provided', async () => {
callMethod
.mockReturnValue(new Error('cannot login'))
.mockName('callMethod');

它工作正常,错误被抛出

我想问题在于,测试结束后,mock 不会被重置。 在我的 jest.conf.js我有 clearMocks: true

每个测试套件都在一个单独的文件中,我在测试之前模拟函数,如下所示:

import simulateQuery from '../../../helpers/simulate-query';


import callMethod from '../../../../imports/api/users/functions/auth/helpers/call-accounts-method';


import LOGIN_WITH_PASSWORD_MUTATION from './mutations/login-with-password';


jest.mock(
'../../../../imports/api/users/functions/auth/helpers/call-accounts-method'
);


describe('loginWithPassword mutation', function() {
...

更新

当我用 .mockImplementation代替 .mockReturnValue时,一切都按预期进行:

callMethod.mockImplementation(() => {
throw new Error('User not found');
});

但这并不能解释为什么在另一个测试中 .mockReturnValue工作得很好..。

186770 次浏览

.mockImplementation改变 .mockReturnValue:

    yourMockInstance.mockImplementation(() => {
throw new Error();
});

如果你想断言的话

   test('the fetch fails with an error', () => {
return expect(fetchData()).rejects.toMatch('error');
});

如果这是一个承诺,你也可以。拒绝 Www.jestjs.io/docs/en/asynchronous#resolves——rejects

角度 + 玩笑:

import { throwError } from 'rxjs';


yourMockInstance.mockImplementation(() => {
return throwError(new Error('my error message'));
});

对于承诺,可以使用 https://jestjs.io/docs/mock-function-api#mockfnmockrejectedvaluevalue

test('async test', async () => {
const asyncMock = jest.fn().mockRejectedValue(new Error('Async error'));


await asyncMock(); // throws "Async error"
});

为了测试是否抛出错误,可以使用 https://eloquentcode.com/expect-a-function-to-throw-an-exception-in-jest

const func = () => {
throw new Error('my error')
}
it('should throw an error', () => {
expect(func).toThrow()
})