Jon Sud
Jon Sud

Reputation: 11661

How to mock only one function in the module?

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(..)
});

Upvotes: 1

Views: 351

Answers (1)

Estus Flask
Estus Flask

Reputation: 222750

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.

Upvotes: 1

Related Questions