Categories
JavaScript Answers

How to test promises in Jest?

Sometimes, we want to test promises in Jest.

In this article, we’ll look at how to test promises in Jest.

How to test promises in Jest?

To test promises in Jest, we can use the resolves.toEqual and rejects.toEqual methods.

For instance, we write

describe('Fetching', () => {
  const filters = {
    startDate: '2015-09-01'
  };
  const api = new TestApi();

  it('should reject if no startdate is given', () => {
    expect.assertions(1);
    return expect(MyService.fetch()).rejects.toEqual({
      error: 'Your code message',
    });
  });


  it('should return expected data', () => {
    expect.assertions(1);
    return expect(MyService.fetch(filters, null, api)).resolves.toEqual(extectedObjectFromApi);
  });
});

to call resolves.toEqual to check the resolve value of the promise returned by MyService.fetch method.

And we call rejects.toEqual to test the rejection message of the promise returned by MyService.fetch().

Conclusion

To test promises in Jest, we can use the resolves.toEqual and rejects.toEqual methods.

Categories
JavaScript Answers

How to mock moment() and moment().format using Jest?

Sometimes, we want to mock moment() and moment().format using Jest.

In this article, we’ll look at how to mock moment() and moment().format using Jest.

How to mock moment() and moment().format using Jest?

To mock moment() and moment().format using Jest, we can call jest.mock.

For instance, we write

const moment = require('moment');

jest.mock('moment', () => {
  return () => jest.requireActual('moment')('2022-01-01T00:00:00.000Z');
});

const tomorrow = () => {
  const now = moment();
  return now.add(1, 'days');
};

describe('tomorrow', () => {
  it('should return the next day in a specific format', () => {
    const date = tomorrow().format('YYYY-MM-DD');
    expect(date).toEqual('2022-01-02');
  });
});

to call jest.mock to mock the moment by passing in a function that returns a function that returns the result of call moment with the given date.

We use requireActual to import moment into our test code.

In the test, we call tomorrow to return the moment date object from the mocked function and call format with the given date.

And then we call expect to check the date string.

Conclusion

To mock moment() and moment().format using Jest, we can call jest.mock.

Categories
JavaScript Answers

How to fix document.getElementById() returns null on component with Jest and Enzyme?

Sometimes, we want to fix document.getElementById() returns null on component with Jest and Enzyme.

In this article, we’ll look at how to fix document.getElementById() returns null on component with Jest and Enzyme.

How to fix document.getElementById() returns null on component with Jest and Enzyme?

To fix document.getElementById() returns null on component with Jest and Enzyme, we can attach the mounted component into the DOM.

For instance, we write:

import {
  mount
} from 'enzyme';

beforeAll(() => {
  const div = document.createElement('div');
  window.domNode = div;
  document.body.appendChild(div);
})

test("Test component with mount + document query selector", () => {
  const wrapper = mount(<YourComponent/>, {
    attachTo: window.domNode
  });
});

to create a div with createElement before any test is run.

And then we call appendChild to append the div to the body element.

Then in a test, we call mount to mount the component we’re testing.

And we set attachTo to the div we created in the beforeAll hook.

Conclusion

To fix document.getElementById() returns null on component with Jest and Enzyme, we can attach the mounted component into the DOM.

Categories
JavaScript Answers

How to fix the Jest ‘No Tests found’ error?

Sometimes, we want to fix the Jest ‘No Tests found’ error.

In this article, we’ll look at to fix the Jest ‘No Tests found’ error.

How to fix the Jest ‘No Tests found’ error?

To fix the Jest ‘No Tests found’ error, we should make sure the testMatch setting in jest.config.js is set to an array of paths with the test files.

For instance, we write

const jestConfig = {
  verbose: true,
  testURL: "http://localhost/",
  'transform': {
    '^.+\\.jsx?$': 'babel-jest',
  },
  testMatch: ['**/__tests__/*.js?(x)'],
}

module.exports = jestConfig

to set testMatch to an array with '**/__tests__/*.js?(x)' to make sure that Jest runs the test files in the __tests__ folder with extension .js or .jsx.

Conclusion

To fix the Jest ‘No Tests found’ error, we should make sure the testMatch setting in jest.config.js is set to an array of paths with the test files.

Categories
JavaScript Answers

How to test for a rejected promise using Jest?

Sometimes, we want to test for a rejected promise using Jest.

In this article, we’ll look at how to test for a rejected promise using Jest.

How to test for a rejected promise using Jest?

To test for a rejected promise using Jest, we can use the rejects.toEqual method.

For instance, we write

it('rejects...', () => {
  const Container = createUserContainer(CreateUser);
  const wrapper = shallow(<Container />);
  expect(wrapper.instance().handleFormSubmit()).rejects.toEqual('error');
});

to call rejects.toEqual with the promise rejection message we want to check for.

It assumes that handleFormSubmit returns a promise.

Conclusion

To test for a rejected promise using Jest, we can use the rejects.toEqual method.