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 badges1 Answer
Reset to default 3I 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');