Home > Software design >  How to run my fixtures for mocha using TypeScript?
How to run my fixtures for mocha using TypeScript?

Time:12-27

Using ExpressJS, TypeScript and Mocha, I want to be able to close my server connection after each test.

I'm aware that I can do something like this on each test file

    this.afterAll(function () {
        server.close();
    });

But this will cause a lot of repetition on my code and I want to do it a little bit more cleaner, so I was reading the Mocha documentation and found about the global fixtures. I created a file called 'fixtures.ts' with the following syntax:

import { app, server } from '../../../app';

export const mochaHooks = (): Mocha.RootHookObject => {
    return {
        afterAll(done: Mocha.Done) {
            console.log('Closing server');
            server.close();
            done();
        },
    };
};

Using this, I want to be able to close my server after the tests end. My problem here is that fixtures.ts isn't doing anything at all when running my tests. My syntax on package.json is something like:

  "scripts": {
    "build": "npx tsc",
    "start": "node build/app.js",
    "dev": "concurrently \"npx tsc --watch\" \"nodemon -q build/app.js\"",
    "test": "mocha --require ts-node/register 'test/{controllers,services}/*.ts' 'test/utils/server/fixtures.ts'",
    "preseed": "npm run build",
    "seed": "node build/test/utils/seeders/seeds.js"
  },

In the mocha documentation, the file extension that the global fixture uses is something like 'mjs' or 'cjs', could this be a problem when using TypeScript?

CodePudding user response:

At the end it was just a typo problem on my package.json. I ended up fixing it using --require after the file name. ts-node does the job for using the global fixture.

  "scripts": {
    "build": "npx tsc",
    "start": "node build/app.js",
    "dev": "concurrently \"npx tsc --watch\" \"nodemon -q build/app.js\"",
    "test": "mocha --require ts-node/register --require 'test/utils/server/fixtures.ts' 'test/{controllers,services}/*.ts' ",
    "seed": "node --require ts-node/register test/utils/seeders/seeds.ts"
  },
  • Related