作者:潘多拉多宝_712 | 来源:互联网 | 2022-12-20 16:49
我正在使用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
我抛出一个错误,因此期望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() {
...
UPDATE
当我.mockReturnValue
用.mockImplementation
预期的一切代替时:
callMethod.mockImplementation(() => {
throw new Error('User not found');
});
但这并不能解释为什么在另一个测试中.mockReturnValue
工作得很好......
1> eduardomoron..:
改变.mockReturnValue
带.mockImplementation
:
yourMockInstance.mockImplementation(() => {
throw new Error();
});