vendredi 19 février 2021

Mocking an imported function's dependencies with jest

I am currently writing tests for a project of mine and I was wondering how to specifically mock an imported function's dependencies. Let me give you an example of what I am trying to achieve:

this is in my module.js and I have 2 functions in it.

const sum = (num1, num2) => {
  return num1 + num2;
};

const performAction = (num1, num2) => {
  return sum(num1, num2);
};

export {sum, performAction}

The implementation of the functions is absolutely irrelevant. The example is just demonstrating how performAction has the sum function as a dependency. How in my test file module.test.js I have code that looks like this:

import { performAction } from "./module";

describe("test performAcction", () => {
  it("work as intended", () => {
    expect(performAction(1, 2)).toEqual(3);
  });
});

I want to replace the implementation of the sum function when I test performAction. I just want to say that I was a solution with dependency injection but I did not like the idea of changing the parameters of my functions, just so I can test them.

I find it astonishing that it's so difficult to do that. Is my approach to testing wrong here at all?

Any feedback and recommendations are welcome.

Aucun commentaire:

Enregistrer un commentaire