Skip to content

Instantly share code, notes, and snippets.

@nickcharlton
Created May 10, 2023 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickcharlton/8a1ab5a0c48a4ca5df3de855baa67d23 to your computer and use it in GitHub Desktop.
Save nickcharlton/8a1ab5a0c48a4ca5df3de855baa67d23 to your computer and use it in GitHub Desktop.
Gist from Drafts

Jest: Changing Mocks per Test

I'd been trying to mock react-native-device-info differently per test, so that I could explore setting a more useful User-Agent based on the platform it was running on. But Jest doesn't make doing this particularly very easy, at least not until recently:

Jest 29 and up

We can use jest.mocked to replace the implementation inside the it:

import { getVersion } from 'react-native-device-info'
import { getUserAgent } from './versions'

jest.mock('react-native-device-info', () => {
  return {
    getVersion: jest.fn(),
  }
})

describe('getUserAgent', () => {
  it('includes version information', () => {
    jest.mocked(getVersion).mockReturnValueOnce('6.0')

    const userAgent = getUserAgent()

    expect(userAgent).toEqual("App Name/6.0")
  })
})

Previous versions of Jest

To satisfy TypeScript types, we need to define a new mock using MockedFunction:

import { getVersion } from 'react-native-device-info'
import { getUserAgent } from './versions'

jest.mock('react-native-device-info', () => {
  return {
    getVersion: jest.fn(),
  }
})

const getVersionMock = getVersion as jest.MockedFunction<typeof getVersion>

describe('getUserAgent', () => {
  it('includes version information', () => {
    getVersionMock.mockReturnValueOnce('6.0')

    const userAgent = getUserAgent()

    expect(userAgent).toEqual("App Name/6.0")
  })
})

This was quite unintuitive to get to (the project had Jest 26), and really needed to be gotten to via the newer implementation helper … it's like doing this was very unexpected!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment