Home > Enterprise >  How to mock only one function in the module?
How to mock only one function in the module?

Time:01-10

I want to mock just the bar function from the bar module.

But when I run the test it's seems jest mocked also the init function.

There is a way to mock only the bar function?

// bar.ts:
export const bar = () => {};
export const init = () => {};

// foo.ts
import { bar } from './bar';

export const foo () => {
  const result = bar();

  return result;
}


// foo.spec.ts
import { bar, init } from './bar';
import { foo } from './foo';

jest.mock('./bar', () => ({ bar: () => { console.log('in bar'); } }));

beforeAll(() => {
 init();
});

it('should', () => {
     
 const result = foo();

 expect(..).toBe(..)
});

CodePudding user response:

It is:

jest.mock('./bar', () => ({
  ...jest.requireActual('./bar'),
  bar: jest.fn()
}));

As a rule of thumb, mocked functions should be Jest spies, this allows to assert calls and change the implementation where needed.

  •  Tags:  
  • Related