简体   繁体   中英

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 ?

playground: https://repl.it/repls/WoodenElectricInstances

Thanks @ltamajs, I found solution .

Need to rewrite module to

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

function reverseAdd(a, b) {
  module.exports.add(b, a); <----- here changes
}

module.exports = {
  add,
  reverseAdd
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM