A library I'm using is structured as
declare namespace foo {
function bar();
};
declare namespace foo.bar {
function baz();
};
So the two functions I need to mock are foo.bar()
and foo.bar.baz()
.
To mock foo.bar()
I was previously using
require('foo');
jest.mock('foo', () => ({
bar: () => mockedBar,
}));
Is there any way to mock foo.bar.baz()
? I tried
jest.mock('foo.bar', () => ({
}));
But it's showing a message Cannot find module 'foo.bar' from 'functions.test.js'
.
You can define a custom mock for your module in a __mocks__
folder in your project root (defined in jest config!). So you can create __mocks__/foo.js
with mocked foo
module functions and Jest automatically loads this module for test purposes. Also you can specify custom path to your mock:
jest.mock('foo', () => jest.requireActual('../some/another/folder/foo.js'));
Check a Jest manual for more info
If 'foo' is under global, you may try adding codes below in the beginning of test script. Or write them in a .js file in and import it in the first line.
Object.defineProperty(global, "foo", {
value: {
bar: {
baz: ()=>{
return true;
},
},
},
},
});
Or simply
global["foo"] = {
bar: {
baz: () => {
return true;
},
},
};
to mock one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With