Categories
JavaScript Answers

How to check if a string contains ‘abc’ or ‘cde’ with Jest?

Sometimes, we want to check if a string contains ‘abc’ or ‘cde’ with Jest.

In this article, we’ll look at how to check if a string contains ‘abc’ or ‘cde’ with Jest.

How to check if a string contains ‘abc’ or ‘cde’ with Jest?

To check if a string contains ‘abc’ or ‘cde’ with Jest, we can call toMatch with a regex that matches both strings.

For instance, we write

expect(str).toMatch(/(abc|cde)/i)

to check if str is 'abc' or 'cde' in a case-insensitive manner.

The i flag lets us check for str in a case-insensitive manner.

Conclusion

To check if a string contains ‘abc’ or ‘cde’ with Jest, we can call toMatch with a regex that matches both strings.

Categories
JavaScript Answers

How to mock a Node module with Jest?

Sometimes, we want to mock a Node module with Jest.

In this article, we’ll look at how to mock a Node module with Jest.

How to mock a Node module with Jest?

To mock a Node module with Jest, we can use the jest.createMockFromModule method.

For instance, we write

const utils = jest.createMockFromModule('../utils').default;
utils.isAuthorized = jest.fn(secret => secret === 'abc');

test('jest.createMockFromModule mocks utils module', () => {
  expect(utils.authorize.mock).toBeTruthy();
  expect(utils.isAuthorized('abc')).toEqual(true);
});

to call jest.createMockFromModule to mock the ./utils module.

Then we set utils.isAuthorized to a mocked function created by jest.fn with a callback to mock its implementation.

Next, we check if utils.authorize.mock is present with expect.

And we call utils.isAuthorized('abc') to see if it returns true as expected.

Conclusion

To mock a Node module with Jest, we can use the jest.createMockFromModule method.

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.