jeudi 1 novembre 2018

Jest doesn`t mock(set spy) on needed function

My test function reverseAdd call another function add that is defined in same module. I need to test, if test function call another.

Module

function add(a, b) {
  return a + b;
}

function reverseAdd(a, b) {
  add(b, a);
}

module.exports = {
  add,
  reverseAdd
}

Test

const exp = require('./add');

describe('add', () => {
  it('should add two numbers', () => {
    expect(exp.add(1, 2)).toBe(3);
  });

  it('should add two numbers', () => {
    exp.add = jest.fn();

    exp.reverseAdd();

    expect(exp.add).toHaveBeenCalledTimes(1);
  });
});

Result

Expected mock function to have been called one time, but it was called zero 

As I understand wraped function is another function, and it is not called in test function.

How can I wrap/spy the function add?

Aucun commentaire:

Enregistrer un commentaire