Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest spyOn a function not Class or Object type

I am familiar with setting spies on Class or Object methods, but what about when the function is just an export default - such that the method itself is independent, like a utility?

I have some existing code like so:

const Funct1 = props => {
  if(props){
    Funct2(args);
  }
  // or return something
};
const Funct2 = props => {
  // do something
  return true
};
export default Funct1;  //Yes the existing export is named the same as the "entry" method above.

And, for example, I'd like to spy on Funct1 getting called and Funct2 returns true.

import Funct1 from "../../../src/components/Funct1";
describe("Test the Thing", () => {
    it("New Test", () => {
        let props = {
            active: true,
            agentStatus: "online"
        };
        const spy = spyOn(Funct2, "method name"); <-- how doe this work if not an obj or class?

        Funct1(props);
        //If I try Funct2(props) instead, terminal output is "Funct2 is not defined"

        expect(spy).toHaveBeenCalledWith(props);
    });
});
like image 585
Phil Lucks Avatar asked Mar 23 '18 19:03

Phil Lucks


People also ask

How do you spyOn a function in jest?

To spy on an exported function in jest, you need to import all named exports and provide that object to the jest. spyOn function. That would look like this: import * as moduleApi from '@module/api'; // Somewhere in your test case or test suite jest.

What is jest Unmock?

unmock(moduleName) ​ Indicates that the module system should never return a mocked version of the specified module from require() (e.g. that it should always return the real module).

How do you make a mock object in jest?

In Jest, Node. js modules are automatically mocked in your tests when you place the mock files in a __mocks__ folder that's next to the node_modules folder. For example, if you a file called __mock__/fs. js , then every time the fs module is called in your test, Jest will automatically use the mocks.


2 Answers

I am not expert in jest, but my recommendation to think about:

1) When the function is exported as default I use something like:

import Funct1 from "../../../src/components/Funct1";
...
jest.mock("../../../src/components/Funct1");
...
expect(Funct1).toHaveBeenCalledWith(params);

2) When the module (utils.js) has multiple exports as

export const f1 = () => {};
...
export const f8 = () => {};

You can try

import * as Utils from "../../../src/components/utils"
const f8Spy = jest.spyOn(Utils, 'f8');
...
expect(f8Spy).toHaveBeenCalledWith(params);

Similar discussion here

like image 101
Дмитрий Дорогонов Avatar answered Nov 16 '22 01:11

Дмитрий Дорогонов


Wrap your function with jest.fn. Like this:

const simpleFn = (arg) => arg;
const simpleFnSpy = jest.fn(simpleFn);
simpleFnSpy(1);
expect(simpleFnSpy).toBeCalledWith(1); // Passes test
like image 21
callOfCode Avatar answered Nov 16 '22 02:11

callOfCode