September 13, 2019

Unit Testing React App with Jest, By Mocking PouchDB Node Module.

Unit Testing React App with Jest, By Mocking PouchDB Node Module.

While doing unit testing of a DB client in our app, we do not really want to make remote DB calls to test the helper functions and their return values. Easiest way to test those functions is by mocking the modules and their functions so we do not need the actual calls to DB.

Jest provides way to mock functions as well as mock implementation of a library module. Let us try the example of library pouchDB which helps in creating a DB client to a remote CouchDB instance. In this example we will be using pouchDB api db.get() to mock and test the helper function using this api.

To begin with, we are using the basic React App created using yarn create react-app my-app . More details about it is here: https://github.com/facebook/create-react-app

1. Let us add the pouchdb library to the package.json created in /my-app under dependencies and do yarn install. (for details about adding pouchdb library to your app, you can refer to: https://pouchdb.com/)

2. Let us create a helper for DB calls , let us call the helper file as db.js. This is how the db.js and its content look:

For now the helper will use single api from pouchdb module, i.e db.get()

3. Let us create a test file for the helper. We need a mock module for pouchdb with db.get() having a mock implementation. So first we need to use automatic mock for pouchdb module, and also implement custom version of the api get() to use in our tests.

As step 1 :

// generate a manual mock for pouchdb client, by using automatic mock and then override the api needed.
jest.genMockFromModule('pouchdb');

Now, implement the mock api needed and create a mock module and override in module as:

const mockDb = {
get: jest.fn(),
plugin: jest.fn(),
};
PouchDB.mockImplementation(() => mockDb);

That's it! write the test for the helper function fetchDoc() now, to test. The completed test file will look like: