我正在使用 Jest 测试我的 GraphQL api。
我为每个查询/变异使用单独的测试套件。
我有 2 个测试(每个测试套件分开),其中我模拟了一个函数(即 Meteor 的 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
中我抛出了一个错误,因此期望 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
能够正常运行...