如何正确地使模拟在 Jest 中抛出错误? [英] How to properly make mock throw an error in Jest?
问题描述
我正在使用 Jest 测试我的 GraphQL api.
I'm testing my GraphQL api using Jest.
我为每个查询/变异使用单独的测试套装
I'm using a separate test suit for each query/mutation
我有 2 个测试(每个测试都在单独的测试套件中),其中我模拟了一个用于突变的函数(即 Meteor 的 callMethod
).
I have 2 tests (each one in a separate test suit) where I mock one function (namely, Meteor's callMethod
) that is used in mutations.
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)
我得到 p>
When I console.log(result)
I get
{ data: { forgotPassword: true } }
这种行为不是我想要的,因为在 .mockReturnValue
中我抛出了一个错误,因此期望 result
有一个错误对象
This behaviour is not what I want because in .mockReturnValue
I throw an Error and therefore expect result
to have an error object
然而,在这个测试之前,运行了另一个
Before this test, however, another is ran
it('should throw an error if wrong credentials were provided', async () => {
callMethod
.mockReturnValue(new Error('cannot login'))
.mockName('callMethod');
它工作正常,错误被抛出
And it works fine, the error is thrown
我想问题在于测试完成后模拟不会重置.在我的 jest.conf.js
我有 clearMocks: true
I guess the problem is that mock doesn't get reset after the test finishes.
In my jest.conf.js
I have clearMocks: true
每个测试套件都在一个单独的文件中,我在测试之前模拟函数,如下所示:
Each test suit is in a separate file, and I mock functions before tests like this:
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
时,一切都按预期进行:
When I substituted .mockReturnValue
with .mockImplementation
everything worked out as expected:
callMethod.mockImplementation(() => {
throw new Error('User not found');
});
但这并不能解释为什么在另一个测试中 .mockReturnValue
工作正常...
But that doesn't explain why in another test .mockReturnValue
works fine...
推荐答案
Change .mockReturnValue
with .mockImplementation
:
Change .mockReturnValue
with .mockImplementation
:
yourMockInstance.mockImplementation(() => {
throw new Error();
});
如果这是一个承诺,你也可以 .rejects www.jestjs.io/docs/en/asynchronous#resolves--rejects
If it's a promise you can also to .rejects www.jestjs.io/docs/en/asynchronous#resolves--rejects
这篇关于如何正确地使模拟在 Jest 中抛出错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!