Code Your Greens

Mock Primitives

Mock a primitive

If you just use the simple syntax of jest.mock('./greeter') to mock out the whole file, you'll find that the primitive values remain untouched.

What doesn't work:

// greeter.ts
const myPrimitive = 'hi world'
// greeter.test.ts
jest.mock('./greeter')
describe('primitives', () => {
it('should mock a primitive', () => {
expect(myPrimitive).toBeUndefined() // error, will give 'hi world'
})
})

What will work:

If you really want to use a fake value for a primitive inside a test, here's how you can do it:

// greeter.ts
const myPrimitive = 'hi world'
// greeter.test.ts
jest.mock('./greeter', () => ({
myPrimitive: 'hi jest'
}))
describe('primitives', () => {
it('should mock a primitive', () => {
expect(myPrimitive).toEqual('hi jest')
})
})

You can also successfully provide fake values for primitives using a file mock.

Scoping a mock primitive between tests

Unfortunately I don't have as of yet a clean way to change the value of a primitive between different tests in the same file.

Since we are working with primitives, and not functions, we can't call jest.fn() to get a mock function and then call mockImplementation or mockReturnValue on it to help us.

You can't even specify a reference to a primitive variable and pass it into the mocked module (which would then allow you to very neatly change the value between tests):

let mockMyPrimitive = 'hi'
jest.mock('./greeter', () => ({
myPrimitive: mockMyPrimitive
}))
// test body
expect(mockMyPrimitive).toEqual('hi') // error: undefined
mockMyPrimitive = 'bye'
expect(mockedPrimitive).toEqual('bye') // error: undefined

If you really need to do this, you'll need to re-declare the whole mock inside a describe block and then keep resetting all the mocks between groups of tests.