Gonzalo Pincheira Arancibia Gonzalo Pincheira Arancibia - 3 months ago 14
Javascript Question

Mocha: Approach to Testing instance of express.Router

I've been designing a javascript controller file and I want to testing if the instance of my controller have a instance of the express's method

Router()
.

import {expect} from 'chai';
import {UF_Controller} from '../../controllers/uf.controller.js';

describe('UF Controller', UFControllerDescription);

function UFControllerDescription(){
it('1. Should be have a express router instance', spec1);

function spec1(){
expect(UF_Controller.router).itself.to.respondTo('get');
expect(UF_Controller.router).itself.to.respondTo('post');
expect(UF_Controller.router).itself.to.respondTo('put');
expect(UF_Controller.router).itself.to.respondTo('delete');
}
}


and my controller

import express from 'express';
import { uf } from '../models/uf.model';

class UFController{

constructor(){
this.router = express.Router();
this.router.get('/', this.getAll);
}

getAll(req, res, next){
res.json(uf.todayUF());
}

getUF(req, res, next){
}

insertUF(req, res, next){
}

replaceUF(req, res, next){
}

updateUF(req, res, next){
}

deleteUF(req, res, next){
}
}

export const UF_Controller = new UFController();


My question is:
This is a valid way check an instance of the express router???

Answer

There's no need to duck-type Express router.

express.Router isn't a constructor an doesn't establish normal prototype chain that can be detected with instanceof. Instead, it establishes prototype chain manually via hacky mixin technique.

It can be tested with

expect(Object.getPrototypeOf(UF_Controller.router)).to.equal(express.Router);
Comments