最佳答案
我正在使用 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
工作得很好..。