Start writing Unit Test of mongoose model using Test Jest

Get Started

Install Jest using yarn:

yarn add --dev jest

npm:

 npm install --save-dev jest

More detail about jest https://jestjs.io/docs/en/getting-started

 

we need mongodb-memory-server-core package.  This package spins up a actual/real MongoDB Server programmatically from node for testing or mocking during development. By default it holds the data in memory. Fresh spinned up mongod process takes about 7Mb of memory. The server will allow you to connect your favorite ODM or client library to the MongoDB Server and run integration tests isolated from each other.

 

more about it https://github.com/nodkz/mongodb-memory-server

See the example:

UserModel.js looks like bellow

const { model } = require('mongoose');
const UserSchema = require('../schemas/UserSchema');

const BaseModel = model('User', UserSchema);


async function createUser({ username }) {
  const user = await BaseModel.create({
    username
  });
  return user;
}

module.exports.createUser = createUser;

UserModel.test.js looks like bellow

const mongoose = require('mongoose');
const { model } = require('mongoose');
const { MongoMemoryServer } = require('mongodb-memory-server-core');
const UserModel = require('./UserModel');
const UserSchema = require('../schemas/UserSchema');

const User = model('User', UserSchema);

describe('user model', () => {
  beforeAll(async () => {
    this.mongoMemoryServer = new MongoMemoryServer();
    const mongoUri = await this.mongoMemoryServer.getUri();
    await mongoose.connect(mongoUri,
      {
        useNewUrlParser: true,
        useFindAndModify: false,
        useUnifiedTopology: true,
      },
      (err) => {
        if (err) console.error(err);
      });
  });

  afterAll(async () => {
    await mongoose.disconnect();
    await this.mongoMemoryServer.stop();
  });

  it('should create new user', async () => {
    await User.deleteMany();
    const mockUser = { username: 'delwar'};
    const userModel = await UserModel.createUser(mockUser);
    expect(userModel.username).toBe(mockUser.username);
  });
});

.eslintrc.json configuration

{
  "plugins": ["jest"],
  "extends": [
    "airbnb-base",
    "plugin:jest/all"
  ],
  "rules": {
    "no-use-before-define": "off",
    "no-underscore-dangle": "off",
    "jest/no-disabled-tests": "warn",
    "jest/no-focused-tests": "error",
    "jest/no-identical-title": "error",
    "jest/prefer-to-have-length": "warn",
    "jest/valid-expect": "error",
    "jest/no-hooks": "off",
    "jest/prefer-expect-assertions": "off",
    "jest/no-test-callback": "off"
  },
  "env": {
    "jest/globals": true
  }
}

 

jest.config.js configuration

module.exports = {
  testEnvironment: 'node',
};

Now we are done.

You May Also Like

About the Author: Md. Delwar Hossain

He has 11 years of experience in developing standalone software and web applications for multiple database platforms. He has been passionate about new tools and technologies. He is positive and trustworthy. He is capable to learn and adapt quickly to different situations. He is a great team player and enjoys leading and mentoring. He is specialized in architecting and building complex web and mobile application. He has strong skills to automate POS, inventory, supply chain, trading export/ import, human resource management, manufacturing and production, distribution management system and hospital management system.

Leave a Reply

Your email address will not be published. Required fields are marked *