简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM