Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a function jest but jest calling original function

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?

like image 972
donut Avatar asked Jun 28 '18 13:06

donut


1 Answers

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.

like image 163
Herman Starikov Avatar answered Oct 10 '22 09:10

Herman Starikov