Javascript 如何正确地使模拟在 Jest 中抛出错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49835264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:29:58  来源:igfitidea点击:

How to properly make mock throw an error in Jest?

javascriptmeteorgraphqljestjs

提问by Le garcon

I'm testing my GraphQL api using Jest.

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

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

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

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.

我有 2 个测试(每个测试都在一个单独的测试套件中),我模拟了一个callMethod用于突变的函数(即 Meteor's )。

  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: '[email protected]' };

    const result = await simulateQuery({ query, params });

    console.log(result);

    // test logic
    expect(callMethod).toBeCalledWith({}, 'forgotPassword', {
      email: '[email protected]',
    });

    // test resolvers
  });

When I console.log(result)I get

console.log(result)我得到

{ data: { forgotPassword: true } }

This behaviour is not what I want because in .mockReturnValueI throw an Error and therefore expect resultto have an error object

这种行为不是我想要的,因为.mockReturnValue我抛出了一个错误,因此期望result有一个错误对象

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

And it works fine, the error is thrown

它工作正常,错误被抛出

I guess the problem is that mock doesn't get reset after the test finishes. In my jest.conf.jsI have clearMocks: true

我想问题是测试完成后模拟不会重置。在我的jest.conf.js我有 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() {
...

UPDATE

更新

When I substituted .mockReturnValuewith .mockImplementationeverything worked out as expected:

当我.mockReturnValue.mockImplementation一切都按预期进行替换时:

callMethod.mockImplementation(() => {
  throw new Error('User not found');
});

But that doesn't explain why in another test .mockReturnValueworks fine...

但这并不能解释为什么在另一个测试中.mockReturnValue工作正常......

回答by eduardomoroni

Change .mockReturnValuewith .mockImplementation:

更改.mockReturnValue.mockImplementation

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

回答by AngularBoy

Accepted answer didn't work for me however this did (Angular + Jest):

接受的答案对我不起作用,但是这样做(Angular + Jest):

import { throwError } from 'rxjs';

yourMockInstance.mockImplementation(() => {
  return throwError(new Error('my error message'));
});