UP | HOME

Mock testing any front-end projects with Jest

The problem when setting up unit test for an existing front-end project is that for any module you want to test, it will coupled with many other modules. So you will need to mock the stuffs that are not related to the functionality you're testing.

The point is, mock everything that are not related to your test cases.

With jest, you can use jest.mock to mock modules, or jest.fn() to define an empty object,…

Let's consider the exist module in a front-end project like this:

File: internal/shared/utils.js

const moment = require('moment');
(function() {
  require("Internal/some-module");

  Foo.utils.formatPrice = function(price) {
    var correctPrice = (price+'').replace(/(\d+.\d{0,2})\d*$/, "$1");
    return Math.round(parseFloat(correctPrice) * 100) / 100;
  };

  Foo.utils.insertView = function(el) {
    $(document).append(el);
  };
});

In the above snippet, we have a typical front-end code that has dependencies with external libraries, some internal modules, and even jQuery, code are wrapped in IIFEs,… And we want to test just the Foo.utils.formatPrice function.

We can start the test by mocking and importing some stuffs:

File: internal/shared/utils.test.js

beforeEach(() => {
  jest.mock('Internal/some-module', () => {
    return {};
  }, { virtual: true });

  window.Foo = jest.fn();
  window.$ = require('jquery');

  jest.resetModules();

  require('./utils');
});

Since we're not gonna use anything in Internal/some-module, it's safe to mock this module as an empty object. We gonna have to use jQuery in some test cases, so we can just import it for real. The Foo object here can be mock as an empty object. Finally, we can import the actual utils.js module for testing. All of these steps happen in a beforeEach() function, which will be executed before any test cases.

Now it's time to write our actual test code:

File: internal/shared/utils.test.js

describe('formatPrice testing', () => {
  it('should working with normal price string', () => {
    expect(Foo.utils.formatPrice('99.9999')).toEqual(99.99);
  });

  it('should not parse invalid input', () => {
    expect(Foo.utils.formatPrice('awe99.99aewf99')).toEqual(NaN);
  });
});

Now run the test with jest command, everything should work.

Date: 2019-01-07 Mon 00:00

Author: Huy Tran

Created: 2019-04-22 Mon 14:41