8

I've found that a mock I'm using, which will return a string, is seemingly returning jest.fn() rather than the "implementation" of the mock being jest.fn().mockImplementation(...).

I'm calling it as so:

const mockDefaultQuery = 'query { mock }'
jest.mock('../functions', () => (
{
    getArticle: jest.fn().mockName('getArticle').mockImplementation(() => {
        return {}
    }),
    defaultQuery: jest.fn().mockImplementation(() => {
        return mockDefaultQuery
    })
})
)

but the call to defaultQuery from the imported 'functions' library returns [Function mockConstructor] in the test scope rather than "query { mock }" as defined by the const it should be returning.

I've also tried using jest.fn().mockReturnValue(mockDefaultQuery) but to no avail.

Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
Bauza23
  • 191
  • 3
  • 18

1 Answers1

1

The problem is that jest.mock will be hoisted at the top of your test file during compilation, have a look here. So you can never use something in the module scope inside of the mock definition. So your code is evaluated like this

jest.mock('../functions', () => (
{
    getArticle: jest.fn().mockName('getArticle').mockImplementation(() => {
        return {}
    }),
    defaultQuery: jest.fn().mockImplementation(() => {
        return mockDefaultQuery
    })
})
)
const mockDefaultQuery = 'query { mock }'

What I normally do in this cases is to create an empty mock and fill it up afterwards:

jest.mock('../functions', () => jest.fn())
import myFunction from '../functions'
const mockDefaultQuery = 'query { mock }'
myFunction.mockImplementation( () => (
{
    getArticle: jest.fn().mockName('getArticle').mockImplementation(() => {
        return {}
    }),
    defaultQuery: jest.fn().mockImplementation(() => {
        return mockDefaultQuery
    })
}))
Andreas Köberle
  • 106,652
  • 57
  • 273
  • 297
  • 1
    Hmm I was still getting a similar behaviour after implementing that pattern. What I did notice resolved the issue was to convert what I was mocking from a const to a function. Not sure if the nature of how I was referring to the const was preventing the mock to call it's implementation (i.e. defaultQuery vs defaultQuery()) but it's an acceptable work around for me for now! – Bauza23 Mar 12 '18 at 13:18