Drico
Drico

Reputation: 1370

Mock a function called by a tested function of the same file with jest

I have a file exporting two functions a and b, where b makes a call to a.

I would like to mock a test that when I call b, it calls a with some parameters, but since the two functions are in the same file, I can't find any way of doing this.

functions.js

export const a = (x) => { a very complicated function };

export const b = (x) => a(x+1);

functions.test.js

import { a, b } from './functions';

describe('b', () => {
  test('calling b calls a with x+1', () => {
    const fakeA = //mock function a ... don't know how to.
    b(1);
    expect(fakeA).toHaveBeenCalledWith(2);
  });
});

Upvotes: 7

Views: 6569

Answers (2)

Drico
Drico

Reputation: 1370

After lots of research, I found 2 ways to achieve this :

  • The first way is to call exports.a instead of a in the b function :

functions.js

export const a = (x) => { a very complicated function };

export const b = (x) => exports.a(x+1);

functions.test.js

import * as functions from './functions';

describe('b', () => {
  test('calling b calls a with x+1', () => {
    functions.a = jest.fn();
    functions.b(1);
    expect(functions.a).toHaveBeenCalledWith(2);
  });
});

});
  • The second way is to change the prototype of b to accepts a function, defaulting to a:

functions.js

export const a = (x) => { a very complicated function };

export const b = (x, a = exports.a) => a(x + 1);

functions.test.js

import { a, b } from './functions';

describe('b', () => {
  test('calling b calls a with x+1', () => {
    const fakeA = jest.fn();
    b(1, fakeA);
    expect(fakeA).toHaveBeenCalledWith(2);
  });
});

Upvotes: 2

Alexus
Alexus

Reputation: 1973

The easiest way to solve this is using jest.spyOn method.

jest.spyOn(object, methodName)

Creates a mock function similar to jest.fn but also tracks calls to object[methodName]. Returns a Jest mock function.

import * as functions from '../functions';


describe('b', () => {
  test('calling b calls a with x+1', () => {

    const fakeA = jest.spyOn( functions, 'a' );

    functions.b(1);

    expect( fakeA ).toHaveBeenCalledWith(2);
  });
});

Upvotes: 2

Related Questions