【发布时间】:2018-09-24 21:24:14
【问题描述】:
我正在使用 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');
而且它工作正常,错误被抛出
我想问题是测试完成后模拟没有被重置。
在我的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() {
...
更新
当我将 .mockReturnValue 替换为 .mockImplementation 时,一切都按预期进行:
callMethod.mockImplementation(() => {
throw new Error('User not found');
});
但这并不能解释为什么在另一个测试中 .mockReturnValue 工作正常...
【问题讨论】:
-
看起来你的模拟是返回一个错误对象,而不是抛出它。在没有看到您正在测试的代码的情况下,我只能分享我的经验。我忘记模拟在我的突变中调用的函数,这导致无意中抛出错误。也许你也遇到过类似的事情?
标签: javascript meteor graphql jestjs