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:
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")
})
})
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!