-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to mock specific module function? #936
Comments
Upon deeper analysis, it appears that jest-mock generates an AST for the whole module, then uses that AST to create a mocked module that conforms to original's exports: https://github.com/facebook/jest/tree/master/packages/jest-mock Other testing frameworks, such as Python's mock (https://docs.python.org/3/library/unittest.mock-examples.html), let you mock specific functions. This is a fundamental testing concept. I highly recommend the ability to mock a portion of a module. I think that jest-mock should be changed to conditionally ignore exports from mocking, and reference the original implementation. |
You can do: jest.unmock('./myModule.js');
const myModule = require('myModule');
myModule.foo = jest.fn(); See http://facebook.github.io/jest/docs/api.html#mock-functions |
I think you have a fundamental misunderstanding of how In your example, if you call Therefore, the example you described is inadequate for the problem I have. Do you know something I don't? |
I do believe I understand this quite well. The way babel compiles modules however doesn't make this easier to understand and I understand your confusion. I don't know exactly how this would behave in a real ES2015 environment with modules, mainly because no such environment exists right now (except maybe latest versions of Chrome Canary, which I haven't tried yet). In order to explain what happens, we have to look at the compiled output of your babel code. It will look something like this: var foo = function foo() {};
var bar = function bar() { foo(); };
exports.foo = foo;
exports.bar = bar; In this case, it is indeed correct that you cannot mock foo and I apologize for not reading your initial issue correctly, however it did not make any assumption on how However, if you change your code to this: var foo = function foo() {};
var bar = function bar() { exports.foo(); };
exports.foo = foo;
exports.bar = bar; and then in your test file you do: var module = require('../module');
module.foo = jest.fn();
module.bar(); it will work just as expected. This is what we do at Facebook where we don't use ES2015. While ES2015 modules may have immutable bindings for what they export, the underlying compiled code that babel compiles to right now doesn't enforce any such constraints. I see no way currently to support exactly what you are asking in a strict ES2015 module environment with natively supported modules. The way that The right solution in your example is not to mock foo but to mock the higher-level API that foo is calling (such as XMLHttpRequest or the abstraction that you use instead). |
@cpojer Thank you for your detailed explanation. I'm sorry if I offended you with my language, I am very efficient with my engineering writing and I want to get my point across ASAP. To put things into perspective, I spent 5 hours of time trying to understand this issue and wrote 2 detailed comments, then you closed it with a brief message that completely missed the point of both of my statements. That is why my next message said you had a "fundamental misunderstanding", because either 1) you did not understand the point I was making, or 2) you didn't understand I will ponder a possible solution to my problem, to get around it for now I mocked a lower level API, but there should definitely be a way to mock the function directly, as that would be quite useful. |
I agree it would be useful to be able to do this, but there isn't a good way in JS to do it without (probably slow) static analysis upfront :( |
@cpojer: I'm unsure if jumping in here 5 months later is the way to go but I couldn't find any other conversations about this. Jumping off from your suggestion above, I've done this to mock out one function from another in the same module: jest.unmock('./someModule.js');
import someModule from './someModule.js';
it('function1 calls function 2', () => {
someModule.function2 = jest.fn();
someModule.function1(...);
expect(someModule.function2).toHaveBeenCalledWith(...);
}); This works for the one test, but I haven't found a way to accomplish this in a way that's isolated to just the one |
You can call |
Hey @cpojer! I am using Jest 16. Neither |
@cpojer -
I'm new to Jest and I'm struggling with a similar problem. I'm using axios, which under the hood uses Thanks! |
yeah, something like this should get you on the right path! :) Use |
@cpojer regarding your comment here: #936 (comment) How would you do that with ES2015? // myModyle.js
export foo = (string) => "foo-" + string
export bar = (string2) => foo(string2)
// myModule.test.js
var module = require('./myModule');
// how do I mock foo here so this test passes?
expect(bar("hello")).toEqual("test-hello") |
For anyone who comes across this looking for a solution, the following seems to be working for me when exporting many const/functions in one file, and importing them in a file which I'm testing function mockFunctions() {
const original = require.requireActual('../myModule');
return {
...original, //Pass down all the exported objects
test: jest.fn(() => {console.log('I didnt call the original')}),
someFnIWantToCurry: {console.log('I will curry the original') return jest.fn((...args) => original.someFnIWantToCurry(...args)}),
}
jest.mock('../myModule', () => mockFunctions());
const storage = require.requireMock('../myModule');
` |
@ainesophaur, not sure what I am doing wrong here. But it seems it doesn't work ...<codes from comment above>..
// Let's say the original myModule has a function doSmth() that calls test()
storage.doSmth();
expect(storage.test).toHaveBeenCalled(); Test will then fail with: expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called. |
@huyph you'd have to mock your doSmth method and your test method in order for jest to test whether it was called. If you can provide the snippet of your mocking code I can check what's wrong |
@ainesophaur ...uhm. I thought your codes above are for mocking the |
@ainesophaur I tried your code as well. But it did not work for me. It never executes the mock function. So, the expectation is never met. I think this is inherent to the way require works like stated above... I wish there was a solution for this. @cpojer Is there anything new regarding partially mocking modules? |
@rantonmattei & @huyph I'd have to see a snippet of your mock definitions and the test you're running. You have to define your mock before the actual implementation file is required/imported. Its been a while since I've worked with JEST, but I do remember I eventually got it to mock everything I needed to, whether it was a node_modules library or a file in my app. I'm a bit short on time ATM, but here is some of the tests from a project I worked on using Jest. Mocking a file from a dependency Actual function definition in this example is done by react-native.. I'm mocking the file "react-native/Libraries/Utilities/dismissKeyboard.js" This is a mock file under function storeMockFunctions() {
return jest.fn().mockImplementation(() => true);
}
jest.mock('react-native/Libraries/Utilities/dismissKeyboard', () => storeMockFunctions(), { virtual: true });
const dismissKeyboard = require('react-native/Libraries/Utilities/dismissKeyboard');
exports = module.exports = storeMockFunctions; I can't find the test file I used for the above, but it was something like require the module, jest would find it in mocks and then I could do something like
Mocking a file you control export const setMerchantStores = (stores) => storage.set('stores', stores); Test file with mock const { storeListEpic, offerListEpic } = require('../merchant');
function storeMockFunctions() {
const original = require.requireActual('../../common/Storage');
return {
...original,
setMerchantStores: jest.fn((...args) => original.setMerchantStores(...args)),
setMerchantOffers: jest.fn((...args) => original.setMerchantOffers(...args)),
};
}
jest.mock('../../common/Storage', () => storeMockFunctions());
import * as storage from '../../common/Storage';
afterEach(() => {
storage.setMerchantStores.mockClear();
});
it('handle storeListEpic type STORE_LIST_REQUEST -> STORE_LIST_SUCCESS', async () => {
const scope = nock('http://url')
.get('/api/merchant/me/stores')
.reply(200, storeData);
const result = await storeListEpic(ActionsObservable.of(listStores())).toPromise();
expect(storage.setMerchantStores.mock.calls).toHaveLength(1);
expect(await storage.getMerchantStores()).toEqual({ ids: storesApiData.result, list: storesApiData.entities.store});
}); |
thanks for sharing @ainesophaur. I still can't get it to work with jest 18.1. Here are my codes: it('should save session correctly', () => {
function mockFunctions() {
const original = require.requireActual('./session');
return {
...original,
restartCheckExpiryDateTimeout: jest.fn((() => {
console.log('I didn\'t call the original');
})),
}
}
jest.mock('./session', () => mockFunctions());
const mockSession = require('./session');
// NOTE: saveSession() will call the original restartCheckExpiryDateTimeout() instead of my
// mock one. However, mockSession.restartCheckExpiryDateTimeout() does call the mock one
mockSession.saveSession('', getTomorrowDate(), 'AUTH');
// mockSession.restartCheckExpiryDateTimeout(); // does print out "I didn't call the original"
expect(mockSession.restartCheckExpiryDateTimeout).toHaveBeenCalled();
}); In export function saveSession(sessionId, sessionExpiryDate, authToken) {
....
restartCheckExpiryDateTimeout(sessionExpiryDate);
...
}
....
export function restartCheckExpiryDateTimeout(...) {
....
} I can't find a way to resolve this issue. Can I reopen this please? @cpojer |
@huyph the way you're doing the export I'd assign |
I should have added that But I will give what you suggest above a go though. Moving both |
I understand it's not defined in the scope of saveSession. saveSession is
calling the sibling method in the parent scope. I ran into this many times
and what I suggested worked for it
…On May 8, 2017 8:38 PM, "Huy Pham" ***@***.***> wrote:
I should have added that restartCheckExpiryDateTimeout() is an exported
function. Not a locally defined function within saveSession()...
I will give what you suggest above a go though. Thanks
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#936 (comment)>, or mute
the thread
<https://github.com/notifications/unsubscribe-auth/AEeBdsmpOOmzvcUHB3D_-Z7MChIzt10Pks5r37WYgaJpZM4IPGAH>
.
|
Just tried that..I found that: This does NOT work: (i.e the original restartCheckExpiryDateTimeout() is still called) export session = {
saveSession: () => {
session.restartCheckExpiryDateTimeout();
},
restartCheckExpiryDateTimeout: () => {},
} This works: (i.e the mock restartCheckExpiryDateTimeout() is called instead). The difference is the use of export session = {
saveSession: function() {
this.restartCheckExpiryDateTimeout();
},
restartCheckExpiryDateTimeout: () => {},
} It could be a problem with jest transpiling these codes .... |
Try to export them as a class object instead of pojo. I believe the
transpiler does hoist the variables differently. We will get to a working
test, I promise.. Its been about half a year since I was on the project
that used jest but I remember this problem well and I remember eventually
finding a solution.
…On May 9, 2017 12:53 AM, "Huy Pham" ***@***.***> wrote:
Just tried that..I found that:
This does NOT work: (i.e the original restartCheckExpiryDateTimeout() is
still get called)
export session = {
saveSession: () => {
session.restartCheckExpiryDateTimeout();
},
restartCheckExpiryDateTimeout: () => {},
}
This does NOT work: (i.e the original restartCheckExpiryDateTimeout() is
still get called)
export session = {
saveSession: function() {
this.restartCheckExpiryDateTimeout();
},
restartCheckExpiryDateTimeout: () => {},
}
It could be a problem with jest transpiling these codes ....
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#936 (comment)>, or mute
the thread
<https://github.com/notifications/unsubscribe-auth/AEeBdrRQExycPYiGtvm7qYi5G87w6b6Oks5r3_FlgaJpZM4IPGAH>
.
|
@sorahn same issue. |
@ainesophaur not working. module: export const getMessage = (num: number): string => {
return `Her name is ${genName(num)}`;
};
export function genName(num: number): string {
return 'novaline';
} test: function mockFunctions() {
const original = require.requireActual('../moduleA');
return {
...original,
genName: jest.fn(() => 'emilie')
}
}
jest.mock('../moduleA', () => mockFunctions());
const moduleA = require('../moduleA');
describe('mock function', () => {
it('t-0', () => {
expect(jest.isMockFunction(moduleA.genName)).toBeTruthy();
})
it('t-1', () => {
expect(moduleA.genName(1)).toBe('emilie');
expect(moduleA.genName).toHaveBeenCalled();
expect(moduleA.genName.mock.calls.length).toBe(1);
expect(moduleA.getMessage(1)).toBe('Her name is emilie');
expect(moduleA.genName.mock.calls.length).toBe(2);
});
}); test result: FAIL jest-examples/__test__/mock-function-0.spec.ts
● mock function › t-1
expect(received).toBe(expected)
Expected value to be (using ===):
"Her name is emilie"
Received:
"Her name is novaline"
at Object.it (jest-examples/__test__/mock-function-0.spec.ts:22:35)
at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
mock function
✓ t-0 (1ms)
✕ t-1 (22ms)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 0.215s, estimated 1s |
Look at my last few comments above. Specifically the last one. Your
exported methods are calling the locally scoped sibling method vs the
actual exported method (which is where your mock is)
…On May 31, 2017 2:00 AM, "novaline" ***@***.***> wrote:
@ainesophaur <https://github.com/ainesophaur> not working.
module:
export const getMessage = (num: number): string => {
return `Her name is ${genName(num)}`;
};
export function genName(num: number): string {
return 'novaline';
}
test:
function mockFunctions() {
const original = require.requireActual('../moduleA');
return {
...original,
genName: jest.fn(() => 'emilie')
}
}jest.mock('../moduleA', () => mockFunctions());const moduleA = require('../moduleA');
describe('mock function', () => {
it('t-0', () => {
expect(jest.isMockFunction(moduleA.genName)).toBeTruthy();
})
it('t-1', () => {
expect(moduleA.genName(1)).toBe('emilie');
expect(moduleA.genName).toHaveBeenCalled();
expect(moduleA.genName.mock.calls.length).toBe(1);
expect(moduleA.getMessage(1)).toBe('Her name is emilie');
expect(moduleA.genName.mock.calls.length).toBe(2);
});
});
test result:
FAIL jest-examples/__test__/mock-function-0.spec.ts
● mock function › t-1
expect(received).toBe(expected)
Expected value to be (using ===):
"Her name is emilie"
Received:
"Her name is novaline"
at Object.it (jest-examples/__test__/mock-function-0.spec.ts:22:35)
at Promise.resolve.then.el (node_modules/p-map/index.js:42:16)
mock function
✓ t-0 (1ms)
✕ t-1 (22ms)
Test Suites: 1 failed, 1 total
Tests: 1 failed, 1 passed, 2 total
Snapshots: 0 total
Time: 0.215s, estimated 1s
—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
<#936 (comment)>, or mute
the thread
<https://github.com/notifications/unsubscribe-auth/AEeBdv6SafXlTtKo3DNeFWhbL6gV9l0Gks5r_QHjgaJpZM4IPGAH>
.
|
@ainesophaur : I attempted The only approach that works for me is in my comment above: where
This is on Jest 20.0.3 |
@johncmunson That's a good point. However, this example you showed of mocking a module only works if you only need to run Take the example from above...I've added export const message = (): string => {
return 'Hello world';
}
export const foo = (): string => {
return message();
}
export const bar = (): (() => string) => {
return foo;
} Using import * as mockTestModule from './hello';
jest.mock('./hello');
const actualTestModule = jest.requireActual('./hello');
describe('test hello', function () {
afterAll(() => {
jest.restoreAllMocks();
});
// first test doesn't depend on any other method of the module so no mocks
it('should NOT mock message in foo', function () {
const actual = actualTestModule.foo();
expect(actual).toBe('Hello world');
});
// the second I want to mock message in foo
it('should mock message in foo', function () {
jest.spyOn(mockTestModule, 'message').mockReturnValue('my message');
const actual = actualTestModule.foo();
expect(actual).toBe('my message'); // fails
expect(mockTestModule.message).toHaveBeenCalledTimes(1); // never called
});
it('should mock foo in bar', function () {
jest.spyOn(mockTestModule, 'foo').mockReturnValue('my message');
const actual = actualTestModule.bar();
expect(actual()).toBe('my message'); // fails
expect(mockTestModule.message).toHaveBeenCalledTimes(1); // never called
});
}); I even tried mocking them separately with Click to see codeimport * as testModule from './hello';
describe('test hello', function () {
afterAll(() => {
jest.restoreAllMocks();
});
it('should NOT mock message in foo', function () {
const actual = testModule.foo();
expect(actual).toBe('Hello world');
});
it('should mock message in foo', function () {
jest.doMock('./hello', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('./hello');
return {
...originalModule,
message: jest.fn().mockReturnValue('my message'),
};
});
const actual = testModule.foo();
expect(actual).toBe('my message'); // fails
expect(testModule.message).toHaveBeenCalledTimes(1); // never called
});
it('should mock foo in bar', function () {
jest.doMock('./hello', () => {
// Require the original module to not be mocked...
const originalModule = jest.requireActual('./hello');
return {
...originalModule,
foo: jest.fn().mockReturnValue('my message'),
};
});
const actual = testModule.bar()();
expect(actual).toBe('my message'); // fails
expect(testModule.foo).toHaveBeenCalledTimes(1); // never called
});
}); The issue with this approach is that requiring the actual module, then say calling I wish it were this simple but from what I see this does not help for the examples from this thread. If I am missing something here please let me know. I'll gladly admit fault. |
The following works and is a bit shorter:
In Typescript, just
This has the advantage of making life easy to restore original functions and clear mocks. |
Oh, yes also this method is not working if your object only has
Probably need to use |
My mocks are working by using the following: import { unsubscribe } from "../lib/my-lib"
import { MyComponent } from "./index"
test("unsubscribe gets called", () => {
const module = require("../lib/my-lib")
jest.spyOn(
module,
"unsubscribe"
).mockImplementation(() => jest.fn())
const { getByTestId } = render(() => <MyComponent />)
let button = getByTestId("trigger.some.action.button")
fireEvent.press(button)
expect(unsubscribe).toHaveBeenCalled()
}) It doesn't seem so elegant and doesn't scale so easily, it works very well though and suits my cases for now.. but if anybody can suggest any other syntax that would be great! This is the only syntax that seems to be working. |
es6 module code: export const funcA = () => {};
export const funcB = () => {
funcA();
}; After transpiled to CommonJS: "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.funcB = exports.funcA = void 0;
var funcA = function funcA() {};
exports.funcA = funcA; // You can mock or add a spy on this `funcA`
var funcB = function funcB() {
funcA(); // This is still original `funcA`
};
exports.funcB = funcB; There are many ways to solve this situation.
function funcA() {}
exports.funcA = funcA;
function funcB() {
exports.funcA(); // Now, this `exports.funcA` is added a spy or mocked. Keep the same reference to `funcA`
}
exports.funcB = funcB; Or, export let funcA = () => {};
export const funcB = () => {
exports.funcA();
}; unit test results: PASS myModule.test.ts (9.225s)
funcB
✓ should call funcA (3ms)
-------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
myModule.ts | 100 | 100 | 100 | 100 |
-------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.967s
Besides, you need to take a look at this docs: https://nodejs.org/api/modules.html#modules_exports_shortcut, to see what exactly does |
The solution in this stackoverflow post worked for me Basically first you convert all the functions you want to convert to jest.mock('../../utils', () => {
const actualUtils = jest.requireActual('../../utils');
const originalImplementation = actualUtils.someFun;
return {
...actualUtils,
someFun: jest.fn()
.mockImplementation(originalImplementation),
};
});
const utils = require('../../utils'); Then you can use it like normal if you want or mock it like this jest.spyOn(utils, 'someFun').mockReturnValueOnce(true); You can use this to get the original implementation beforeEach(() => {
jest.clearAllMocks();
}); |
Thank you! |
Does not work when the mocked function is called from within the module. |
Also, I found that sometimes it can be useful to mock function the way that you don't change the original function but call function with some custom (additional) variables: jest.mock('./someModule', () => {
const moduleMock = require.requireActual('./someModule');
return {
...moduleMock,
// will mock this function
someFunction: (args) =>
moduleMock.someFunction({
...args,
customArgument,
}),
};
}); In my case I needed to pass come config to function without which it would use default one. This is the only way I found to do this, so if you come up with some better or easier ideas, will be glad to hear :) |
FWIW I've pulled together various approaches with runnable examples in https://github.com/magicmark/jest-how-do-i-mock-x/blob/master/src/function-in-same-module/README.md |
This does not answer the OPs question/issue, but is a solution with some refactoring involved. I've found separating my functions into different files, and then mocking those imports, is the easiest thing to do. // package.json
...
"scripts": {
"test": "jest",
...
"devDependencies": {
"@babel/preset-env": "^7.11.5",
"jest": "^24.9.0",
... // babel.config.js
module.exports = {
presets: [
[
'@babel/preset-env',
{
targets: {
node: 'current',
},
},
],
],
}; // module-utils.js
export const isBabaYaga = () => {
return false
} // module.js
import { isBabaYaga } from './module-utils'
export const isJohnWickBabaYaga = () => {
return isBabaYaga()
} // modules.test.js
import { isJohnWickBabaYaga } from './module';
jest.mock('./module-utils', () => ({
isBabaYaga: jest.fn(() => true)
}))
test('John Wick is the Baba Yaga', () => {
// when
const isBabaYaga = isJohnWickBabaYaga()
// then
expect(isBabaYaga).toBeTruthy()
}); PASS src/module.test.js
✓ John Wick is the Baba Yaga (4ms) |
I've recently run into this issue. None of the proposed solutions work for me because I'm unable to change the code. The babel-plugin-rewire also does not work for me. Is there any other solutions out there to test that a function was called by another function within the same module? This honestly seems like it should work or that there should be a babel plugin out there that does this. Any help would be much appreciated! |
Have you checked out #936 (comment)? There's a minimal repro in there that mocks functions calls in the same file. |
Reading this thread I was unable to find any working solution for TypeScript. This is how I've managed to solve the issue. Moreover, using jest.doMock() it's possible to mock module functions only in some specific tests of a test file and provide an individual mock implementations for each of them. src/module.ts import * as module from './module';
function foo(): string {
return `foo${module.bar()}`;
}
function bar(): string {
return 'bar';
}
export { foo, bar }; test/module.test.ts import { mockModulePartially } from './helpers';
import * as module from '../src/module';
const { foo } = module;
describe('test suite', () => {
beforeEach(function() {
jest.resetModules();
});
it('do not mock bar 1', async() => {
expect(foo()).toEqual('foobar');
});
it('mock bar', async() => {
mockModulePartially('../src/module', () => ({
bar: jest.fn().mockImplementation(() => 'BAR')
}));
const module = await import('../src/module');
const { foo } = module;
expect(foo()).toEqual('fooBAR');
});
it('do not mock bar 2', async() => {
expect(foo()).toEqual('foobar');
});
}); test/helpers.ts export function mockModulePartially(
modulePath: string,
mocksCreator: (originalModule: any) => Record<string, any>
): void {
const testRelativePath = path.relative(path.dirname(expect.getState().testPath), __dirname);
const fixedModulePath = path.relative(testRelativePath, modulePath);
jest.doMock(fixedModulePath, () => {
const originalModule = jest.requireActual(fixedModulePath);
return { ...originalModule, ...mocksCreator(originalModule) };
});
} Mocking functions of a module is moved to helper function |
@ezze Option 1 from @nickofthyme comment worked in TS for me. Then you don't need any helpers. |
@gerkenv Thanks for pointing it out but it requires to replace all function declarations by function expressions that sometimes is not a good option for already existing big projects. |
i'm come form 2021 🤣,nowadays this is more general in typescript and ES2015+. i think jest Integrate this in a new api / override or other way would be better,waiting for ECMA improve this and update unify,not user implement it in every project. this solution still buggy , if mock module have inner reference it's can't be mocked |
Five years late to the party, but if you're using Babel (i.e. I use it in my Jest tests along with spying to intuitively mock only specific module functions without rewriting my source, using TypeScript-incompatible dark magic like The plugin replaces all internal references to each module's own exported items with an explicit reference to those items in the form of a Before: // file: myModule.ts
export function foo() {
// expensive network calls
}
export function bar() {
// ...
foo();
}
export function baz() {
// ...
foo();
} After babel-plugin-explicit-exports-references: // file: myModule.ts
export function foo() {
// expensive network calls
}
export function bar() {
// ...
module.exports.foo();
}
export function baz() {
// ...
module.exports.foo();
} And finally, after // file: myModule.js
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.foo = foo;
exports.bar = bar;
exports.baz = baz;
function foo() {// expensive network calls
}
function bar() {
// ...
module.exports.foo();
}
function baz() {
// ...
module.exports.foo();
} And that's it 🚀 For usage examples, see I use the plugin only when running Jest tests (so: not in production), since it adds needless characters to the bundle. |
If you're coming to this thread to understand how to mock a function called by the function you're testing within the same module, this comment is exactly what you're looking for: #936 (comment) |
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
I'm struggling with something that I think should be both easy and obvious, but for whatever reason I can't figure it out.
I have a module. It exports multiple functions. Here is
myModule.js
:I unmock the module for testing.
jest.unmock('./myModule.js');
However, I need to mock
foo
, because it makes ajax calls to my backend. I want every function in this file to remain unmocked, expect forfoo
, which I want to be mocked. And the functionsbar
andbaz
make calls internally tofoo
, so when my test callsbar()
, the unmockedbar
will call the mockedfoo
.It appears in the jest documentation that calls to
unmock
andmock
operate on the entire module. How can I mock a specific function? Arbitrarily breaking up my code into separate modules so they can be tested properly is ridiculous.The text was updated successfully, but these errors were encountered: