最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论