3

I'm using Jest to test some utility functions.

my_util.js:

export function myFunc(i) {
  if (i === 1){
    anotherFunc();
  }
}

another_util.js:

export function anotherFunc(i) {
    console.log('in anotherFunc');
}

What is the simplest way to test that anotherFunc() was called? Here is my current unit test, which is failing. Is there a way to test that a function was called by it's name?

import { myFunc } from './my_util.js'

...

  it('myFunc should call anotherFunc', () => {
    const anotherFunc = jest.fn();
    myFunc(1);
    expect(anotherFunc).toHaveBeenCalled();  
  });

Results:

Expected number of calls: >= 1
Received number of calls:    0
Gen Tan
  • 858
  • 1
  • 11
  • 26

1 Answers1

-2

Maybe you should just inject anotherFunc to myFunc as argument, it will make testing easier:

function myFunc(i, cb) {
  if (i === 1){
    cb();
  }
}
  it('myFunc should call anotherFunc', () => {
    const anotherFunc = jest.fn();
    myFunc(1, anotherFunc);
    expect(anotherFunc).toHaveBeenCalled();  
  });