Jest.spy mockImplementation only working when importing an object

Viewed 16

Not working code

I am trying to mock an object like so:

// myService.test.ts
Import * as myService from 'Services/myService.ts'

...

jest.spyOn(myService, 'myFunction').mockImplementation(
  () => {
    console.log('MOCK')
  }
)

This is trying to mock this:

// myService.ts
export const myFunction = () => {
  console.log('REAL')
}

This is however not working... instead if I do this is starts working

Working code

// myService.test.ts
Import { myFunctionObj } from 'Services/myService.ts'

...

jest.spyOn(myFunctionObj, 'myFunction').mockImplementation(
  () => {
    console.log('MOCK')
  }
)

This is trying to mock this:

// myService.ts
export const myFunctionObj = { 
  myFunction: () => {
    console.log('REAL')
  }
}

Can someone explain why this is working when using an object but not when trying to mock from the all functions in the file.

Can anyone let me know of a way to do my original way, as I would prefer to not have to add an object with a function inside.

0 Answers
Related