javascript - Mocking multiple named exports in jest.mock(moduleName, factory) factory function - Stack Overflow

I've been using Jest in a small project, and am having trouble with Jest mocks. I have a utility f

I've been using Jest in a small project, and am having trouble with Jest mocks. I have a utility file that exports named custom error constructor functions. I need to mock those functions in my test file. I don't want to use the manual mocking technique shown in the Jest documentation (i.e., putting a mock file in __mocks__), but rather I want to define the mocks in the test file. I am trying something like this in my test file:

const errorMock = () => {
  return {
    configNotFoundError: jest.fn(() => new Error()),
    invalidJSONError: () => jest.fn(() => new Error()),
  }
};

jest.mock('./error', errorMock);

const { configNotFoundError, invalidJSONError } = require('./error');

But I get the following error:

babel-plugin-jest-hoist: The second argument of `jest.mock` 
must be an inline function.

Could someone help me understand what I'm doing wrong?

I've been using Jest in a small project, and am having trouble with Jest mocks. I have a utility file that exports named custom error constructor functions. I need to mock those functions in my test file. I don't want to use the manual mocking technique shown in the Jest documentation (i.e., putting a mock file in __mocks__), but rather I want to define the mocks in the test file. I am trying something like this in my test file:

const errorMock = () => {
  return {
    configNotFoundError: jest.fn(() => new Error()),
    invalidJSONError: () => jest.fn(() => new Error()),
  }
};

jest.mock('./error', errorMock);

const { configNotFoundError, invalidJSONError } = require('./error');

But I get the following error:

babel-plugin-jest-hoist: The second argument of `jest.mock` 
must be an inline function.

Could someone help me understand what I'm doing wrong?

Share Improve this question edited Jan 9, 2018 at 14:11 webstackdev asked Jan 9, 2018 at 0:09 webstackdevwebstackdev 94917 silver badges25 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

I had a similar problem with named exports recently. according to the docs, jest.mock calls are hoisted to the top of the test and are subsequently executed before you define errorMock. Functions seem to be hoisted above these calls. Try:

function errorMock() {
  return {
    configNotFoundError: jest.fn(() => new Error()),
    invalidJSONError: () => jest.fn(() => new Error()),
  }
};

jest.mock('./error', errorMock);

const { configNotFoundError, invalidJSONError } = require('./error');

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745410537a4626510.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信