Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest - how to check if a function is called by another function

I'm using Jest to test some Javascript. In a file, called 'function.js' I have two functions like so:

functions.js

const firstFunc = () => {
  const x = secondFunc()
  return x
}

const secondFunc = () => {
  return '5'
}

module.exports = {
  firstFunc,
  secondFunc
}

In my Jest test file I have:

const functions = require('./functions.js')

test('test if secondFunc is called', () => {
  const mockFunction = jest.fn()
  functions.secondFunc = mockFunction;
  functions.firstFunc()
  expect(mockFunction).toHaveBeenCalled()
})

I've actually tried many different variations of things like this. I'm unable to get jest.fn() to work I want it to. Overall I'm wanting to be able to see information about secondFunc, such as how many times it was called, what parameters with, etc, but I have to actually call firstFunc. Can anyone help me as I can't seem to figure this out.

like image 243
AKD Avatar asked Oct 25 '25 00:10

AKD


1 Answers

You need to do some refactoring. Keep the same reference for secondFunc. Then you can replace it with a mocked object.

functions.js:

const firstFunc = () => {
  const x = exports.secondFunc();
  return x;
};

const secondFunc = () => {
  return '5';
};

exports.firstFunc = firstFunc;
exports.secondFunc = secondFunc;

unit test result:

 PASS  stackoverflow/62583841/functions.test.js (12.17s)
  ✓ test if secondFunc is called (3ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        13.779s
like image 110
slideshowp2 Avatar answered Oct 27 '25 12:10

slideshowp2