Get unlimited public & private packages + package-based permissions with npm Pro.Get started »

jest-mock-primitive

1.0.1 • Public • Published

jest-mock-primitive

Build Status

Ever tried to mock a primitive? You can create a mock within your test file...

jest.mock('./config', () => ({ name: 'Bingo' }))

...but that only works once. If you need to test variations of that, you need to make a new test file for each version.

Unless you use jest-mock-primitive. 😎

Usage

To mock primitives on a file called config.js, add a manual mock. Then export the module after passing it through primitive-mock.

// __mocks__/config.js
import mock from 'jest-mock-primitive'
import path from 'path'
 
// Use module.exports and provide the absolute path.
module.exports = mock(path.resolve(__dirname, '../config'))

Now you can mock primitives just like you mock functions. Each primitive is on the mocked module with the original value, but they also have "backdoor" mocks. To alter or interrogate the mock for name, use nameMock. For color, use colorMock. For evilBananaSpaceShip, use evilBananaSpaceShipMock.

it('should allow me to force feed values for a primitive', () => {
  const { nameMock } = require('./config')
  nameMock.mockImplementationOnce(() => 'Bert')
  expect(app.getName()).toBe('Bert')
 
  nameMock.mockImplementationOnce(() => 'Ernie')
  expect(app.getName()).toBe('Ernie')
})

The rest of the module is mocked via genMockFromModule, so you can use it as usual.

Complete Example

example

Caveats

Due to the way the import * as style of imports breaks references, this does not work without a minor tweak.

For any non-functions you want to mock, the call sites must reference the default export as shown here.

import * as config from './config'
 
// can't mock
// export const getName = () => config.name
 
// can mock
export const getName = () => config.default.name

kickstarted by npm-boom

Install

npm i jest-mock-primitive

DownloadsWeekly Downloads

57

Version

1.0.1

License

ISC

Unpacked Size

219 kB

Total Files

44

Last publish

Collaborators

  • avatar