如何正确地使嘲笑在Jest中引发错误? [英] How to properly make mock throw an error in Jest?

查看:72
本文介绍了如何正确地使嘲笑在Jest中引发错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Jest测试我的GraphQL api.

I'm testing my GraphQL api using Jest.

我为每个查询/突变使用单独的测试服

I'm using a separate test suit for each query/mutation

我有2个测试(每个测试都在单独的测试服中),其中我模拟了一个用于突变的功能(即流星的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)我得到

{ 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');

工作正常,会引发错误

我想问题是测试完成后模拟无法重置. 在我的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...

推荐答案

.mockImplementation更改.mockReturnValue:

yourMockInstance.mockImplementation(() => {
  throw new Error();
});

这篇关于如何正确地使嘲笑在Jest中引发错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆