Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spy same module function in jest?

I am writing unit tests for a function which calls another function inside the same module.

Eg.

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

export function showMessage(a, b) {
  let sum = add(a, b)
  return `The sum is ${sum}`
}

Test:

import * as Logics from './logics;

describe('showMessage', () => {
  it('should return message with sum', () => {
      let addSpy = jest.spyOn(Logics, 'add')
      let  showMessageResponse = Logics.showMessage(2, 2)
      expect(addSpy).toHaveBeenCalledTimes(1)
  });
});

I want to test if the add function is being called when showMessage is executed. The above one is giving the following error:

Expected number of calls: 1 Received number of calls: 0

I have found a solution but that requires changes in the way functions are exported:

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

function showMessage(a, b) {
  const sum = Logics.add(a, b)
  return `The sum is ${sum}`
}

const Logics = {
  showMessage,
  add
}
export default Logics

I do not want to change the way I am exporting the functions.

like image 453
Garima Srivastava Avatar asked May 01 '26 18:05

Garima Srivastava


1 Answers

Ideally you should test function independent. One test is not responsible for another function test functionality.

Not a best approach but you could do something like this:

util.js

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

export function showMessage(a, b, addNew = add) {
  let sum = addNew(a, b);
  return `The sum is ${sum}`;
}

And in your test you could do like this: util.test.js

import * as Logics from "./util";

describe("showMessage", () => {
  it("should return message with sum", () => {
    let addSpy = jest.spyOn(Logics, "add");
    addSpy.mockReturnValue(123);
    let showMessageResponse = Logics.showMessage(2, 2, addSpy);
    expect(addSpy).toHaveBeenCalledTimes(1);
    expect(showMessageResponse).toBe(`The sum is 123`);
  });
});


Here is the sandbox you can play with: https://codesandbox.io/s/jest-test-forked-9zk1s4?file=/util.test.js:0-366

like image 61
Shubham Verma Avatar answered May 04 '26 07:05

Shubham Verma