admin管理员组文章数量:1428993
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');
本文标签:
版权声明:本文标题:javascript - Mocking multiple named exports in jest.mock(moduleName, factory) factory function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745410536a2657446.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论