(unit) Testing moleculer.services application

(unit) Testing moleculer.services application

Abstract

After reading this article, you will know how to ( for moleculer.services)

  • Tests that run on CI
  • Mocks — but not too many
  • DB adaptor tests
  • A structured approach to unit tests for the framework

A few months ago, I started to use the framework extensively including for production use. I am writing TDD, and as such, I have tests covering my code. Recently over the gitter channel, I noticed quite a few people asking how to write the unit test — and decided to write this walkthrough


I use a permanent template for my projects that looks like this

  • I use typescript for my sanity
  • note the new jest typescript runner that I use in favor of ts-jest

Let’s start by approach — Shell we go top-down design (from the API gateway) or from the moving parts. Depends on which state your project is based on the architecture — ( I use The IDesign’s Method you can learn about it here)

  1. if it is in the design phase — developers could do non-core tasks, like utility services, security and so on
  2. If it is in the primary development cycle — the developer must be responsible for the whole chain — and I advise to go top-down all the way

Top-down approach

For the context, let us assume that we create a quote calculation workflow.

Define a test for the entry endpoint API gateway — the most basic one — that it responds to a request

import { ServiceBroker } from 'moleculer';
import * as request from 'supertest';
describe('quote API', () => {
    const TIMEOUT = 2000;
    jest.setTimeout(TIMEOUT);
    const broker = new ServiceBroker({logLevel: 'info', namespace: 'quote-api'});
    const apiSchema = require('../../src/api.service');
    const apiService = broker.createService(apiSchema);
    beforeEach(async () => {
        await broker.start();
    });
    afterEach(async () => {
        await broker.stop();
    });
    test('path responds', async () => {
        await request(apiService.server)
                .get('/quote')
                .expect(200);
    });
});

This test is failing — because our service file still does not exists — let us create it


continue reading on my page at

https://dankuida.com/unit-testing-moleculer-services-application-14247c924f27

To view or add a comment, sign in

More articles by Dan Kuida

Explore content categories