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() {

  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) {

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');



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', () => {

  it('should not parse invalid input', () => {

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

Date: 2019-01-07 Mon 00:00

Author: Huy Tran

Created: 2020-02-09 Sun 15:01