Categories
JavaScript Answers

How to mock import of JSON file with Jest?

Sometimes, we want to mock import of JSON file with Jest.

In this article, we’ll look at how to mock import of JSON file with Jest.

How to mock import of JSON file with Jest?

To mock import of JSON file with Jest, we can use jest.mock.

For instance, we write

jest.mock('path/to/setting.json', () => ({
  foo: 'bar'
}), {
  virtual: true
})

to call jest.mock to mock the path/to/setting.json JSON file.

We pass in a function that returns the JSON object as the 2nd argument and an object with the virtual property set to true to let us mock the JSON file.

virtual set to true lets us mock modules that don’t exist anywhere in the system.

Since a JSON file isn’t a JavaScript module, we need this option to mock it.

Conclusion

To mock import of JSON file with Jest, we can use jest.mock.

Categories
JavaScript Answers

How to check that an argument to a mocked function is a function with Jest?

Sometimes, we want to check that an argument to a mocked function is a function with Jest.

In this article, we’ll look at how to check that an argument to a mocked function is a function with Jest.

How to check that an argument to a mocked function is a function with Jest?

To check that an argument to a mocked function is a function with Jest, we can use the toBeCalledWith method.

For instance, we write

expect(AP.require).toBeCalledWith('messages', expect.any(Function))

to check that AP.require is called with 'messages' and a function respectively.

expect.any(Function) checks that the argument of AP.require is a function.

Conclusion

To check that an argument to a mocked function is a function with Jest, we can use the toBeCalledWith method.

Categories
JavaScript Answers

How to fix mockImplementation() not working in Jest?

Sometimes, we want to fix mockImplementation() not working in Jest.

In this article, we’ll look at how to fix mockImplementation() not working in Jest.

How to fix mockImplementation() not working in Jest?

To fix mockImplementation() not working in Jest, we should call jest.mock with a function that returns an object with the mocks.

For instance, we write

import service from './Service';

jest.mock('./Service', () => jest.fn());

to mock the ./Service module with whatever is returned by jest.fn.

Then we can mock the functions exported in ./Service with

service.func = jest.fn(() => { /*your mock*/ })

We call jest.fn with a function that mocks the implementation of the func function in from service.

Conclusion

To fix mockImplementation() not working in Jest, we should call jest.mock with a function that returns an object with the mocks.

Categories
JavaScript Answers

How to ignore a file pattern for Jest code coverage?

Sometimes, we want to ignore a file pattern for Jest code coverage.

In this article, we’ll look at how to ignore a file pattern for Jest code coverage.

How to ignore a file pattern for Jest code coverage?

To ignore a file pattern for Jest code coverage, we can add the option in the Jest config.

For instance, we add

collectCoverage: true,
collectCoverageFrom: ['src/**/*.ts','!src/*/filesToExclude.ts']

to calculate the code coverage from the paths that match patterns listed in collectCoverageFrom that don’t have the exclamation mark before it.

As a result, we see code coverage calculated from the src/**/*.ts and exclude src/*/filesToExclude.ts from code coverage calculations.

Conclusion

To ignore a file pattern for Jest code coverage, we can add the option in the Jest config.

Categories
JavaScript Answers

How to mock history.push with the new React Router Hooks using Jest?

Sometimes, we want to mock history.push with the new React Router Hooks using Jest.

In this article, we’ll look at how to mock history.push with the new React Router Hooks using Jest.

How to mock history.push with the new React Router Hooks using Jest?

To mock history.push with the new React Router Hooks using Jest, we can call jest.mock to mock the useHistory hook.

For instance, we write

import React from 'react';
import {
  MemoryRouter
} from 'react-router-dom';
import {
  render,
  fireEvent
} from '@testing-library/react';
import RouteNotFound from './NotFound';

const mockHistoryPush = jest.fn();

jest.mock('react-router-dom', () => ({
  ...jest.requireActual('react-router-dom'),
  useHistory: () => ({
    push: mockHistoryPush,
  }),
}));

describe('RouteNotFound', () => {
  it('Redirects to correct URL on click', () => {
    const {
      getByRole
    } = render(
      <MemoryRouter>
        <RouteNotFound />
      </MemoryRouter>,
    );

    fireEvent.click(getByRole('button'));
    expect(mockHistoryPush).toHaveBeenCalledWith('/help');
  });
});

to call jest.mock with a function that returns an object with the actual members of react-router-dom as returned by requireActual.

And then we set useHistory to a function that returns an object with push set to mockHistoryPush.

Then we can use the mock when we call expect.

Conclusion

To mock history.push with the new React Router Hooks using Jest, we can call jest.mock to mock the useHistory hook.