9

I have a function that returns true or false, lets call it myFunc

myFunc (){
  if(something){return true}
  else{return false}
}

that's what it does for sake of arg

I then call it somewhere else

if(myFunc()){

}else{
}

when I log it out, it continually comes out as false. however, when i have mocked it in my test like so:

const myMock = (myModule.myFunc = jest.fn())
myMock.mockReturnValue(true)

so why is it still coming back as false when I log it from the index file? or is that not quite how mocking works?

Joshua
  • 3,055
  • 3
  • 22
  • 37
donut
  • 343
  • 2
  • 7
  • 15

2 Answers2

12

I'm guessing that myModule is the object you imported, and then you set the mock function on that object. But in the myModule file you are referencing that function directly, not through a module reference, right?

The proper way would probably be to move myFunc out of myModule. But if you want to keep it there, then you are going to have to partially mock myModule:

jest.mock('./myModule', () => {
  return {
    ...jest.requireActual('./myModule'),
    myFunc: jest.fn()
  }
})

But seriously consider moving myFunc out of myModule, because partial mocking is difficult and confusing.

Fel
  • 4,428
  • 9
  • 43
  • 94
Herman Starikov
  • 2,636
  • 15
  • 26
0

One way I found to solve my issue was to use a class instead.

Here is a sudo example:

Implementation

export class Location {
  getLocation() {
    const environment = this.getEnvironmentVariable();
    return environment === "1" ? "USA" : "GLOBAL";
  }
  getEnvironmentVariable() {
    return process.env.REACT_APP_LOCATION;
  }
}

Test

import { Location } from "./config";

test('location', () => {
  const config = new Location();
  jest.spyOn(config, "getEnvironmentVariable").mockReturnValue("1")

  const location = config.getLocation();
  expect(location).toBe("USA");
});
Evandro Pomatti
  • 13,341
  • 16
  • 97
  • 165