javascriptunit-testingjestjsfaker.js

How to spy on a fakerjs method call


Faker.js allow you to easily create faked data using for example the following:

import * as faker from 'faker'
console.log(faker.lorem.text())

So I tried to mock this library to spy the use of faker.lorem.text():

import * as faker from 'faker'

const mockFakerLoremText = jest.fn()
jest.mock('faker', () => ({
  lorem: {
    text: mockFakerLoremText
  }
}))


it('should have called lorem.text() method', () => {
  faker.lorem.text()

  expect(mockFakerLoremText).toHaveBeenCalledTimes(1)
})

But then I got the following error:

ReferenceError: Cannot access 'mockFakerLoremText' before initialization

So has someone an idea how I can spy on the call of this method .lorem.text()?


Solution

  • From the docs Calling jest.mock() with the module factory parameter

    A limitation with the factory parameter is that, since calls to jest.mock() are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory

    That's why you got the error.

    An working example using "jest": "^26.6.3":

    index.test.js:

    import * as faker from 'faker';
    
    jest.mock('faker', () => ({
      lorem: {
        text: jest.fn(),
      },
    }));
    
    it('should have called lorem.text() method', () => {
      faker.lorem.text();
    
      expect(faker.lorem.text).toHaveBeenCalledTimes(1);
    });
    

    unit test result:

     PASS  examples/65924623/index.test.ts
      √ should have called lorem.text() method (3 ms)
    
    ----------|---------|----------|---------|---------|-------------------
    File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
    ----------|---------|----------|---------|---------|-------------------
    All files |       0 |        0 |       0 |       0 |
    ----------|---------|----------|---------|---------|-------------------
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        6.913 s, estimated 7 s