Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock a namespace and a function with same name using Jest

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'.

like image 357
Kuba Avatar asked Jul 18 '17 19:07

Kuba


2 Answers

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

like image 143
l2ysho Avatar answered Oct 14 '22 13:10

l2ysho


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.

like image 30
Joe Tse Avatar answered Oct 14 '22 11:10

Joe Tse