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.

Categories
JavaScript Answers

How to stop test suite after first fail with Jest?

Sometimes, we want to stop test suite after first fail with Jest.

In this article, we’ll look at how to stop test suite after first fail with Jest.

How to stop test suite after first fail with Jest?

To stop test suite after first fail with Jest, we can define our own test function.

For instance w ewrite:

let hasTestFailed = false
const sequentialTest = (name, action) => {
  test(name, async () => {
    if (hasTestFailed) {
      console.warn(`[skipped]: ${name}`)
    } else {
      try {
        await action()
      } catch (error) {
        hasTestFailed = true
        throw error
      }
    }
  })
}
describe('Test scenario 1', () => {
  sequentialTest('that item can be created', async () => {
    expect(true).toBe(false)
  })

  sequentialTest('that item can be deleted', async () => {
    //...
  })
})

to define the sequentialTest function that takes the same arguments as test.

In it, we call test with a function that check a test failed by catching the action test callback.

If an error is thrown, then it’s failed and hasTestFailed is set to true.

And we rethrow the error so the test suite will stop running.

Conclusion

To stop test suite after first fail with Jest, we can define our own test function.

Categories
JavaScript Answers

How to pass an object to expect().toBeCalledWith() with Jest?

Sometimes, we want to pass an object to expect().toBeCalledWith() with Jest.

In this article, we’ll look at how to pass an object to expect().toBeCalledWith() with Jest.

How to pass an object to expect().toBeCalledWith() with Jest?

To pass an object to expect().toBeCalledWith() with Jest, we should use the object as the argument of the expect.objectContaining method.

For instance, we write:

expect(api.submitForm).toBeCalledWith(
  expect.objectContaining({
    foo: 'foo',
    bar: 'bar'
  }),
);

to call expect.objectContaining with the object that we want to check api.submitForm is called with.

api.submitForm is the function being spied on.

Conclusion

To pass an object to expect().toBeCalledWith() with Jest, we should use the object as the argument of the expect.objectContaining method.

Categories
JavaScript Answers

How to mock a dependency’s constructor with Jest?

To mock a dependency’s constructor with Jest, we can call jest.mock.

For instance, we write

import * as AWS from 'aws-sdk';

jest.mock('aws-sdk', () => {
  return {
    CloudWatch: jest.fn().mockImplementation(() => {
      return {}
    })
  }
});

test('AWS.CloudWatch is called', () => {
  new AWS.CloudWatch();
  expect(AWS.CloudWatch).toHaveBeenCalledTimes(1);
});

to mock the CloudWatch constructor with a function that returns an empty object.

We call jest.fn to return a mocked function and we mock the return value of the function with mockImplementation.

Then we can use the AWS.CloudWatch constructor to run the mocked version of the constructor.

We still have to import the real dependency with

import * as AWS from 'aws-sdk';

before we can mock AWS.CloudWatch.