Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock dependencies with Mocha and Typescript

Tags:

I have a typescript project which uses mocha. Let's say we have two modules as follows.

// http.ts
export class Http {
}

// app.ts
import Http from './http';

export class App {

}

How could I mock the Http module when I'm testing the App?

The test is executed through the npm script as below.

"test": "cross-env NODE_ENV=test ./node_modules/mocha/bin/mocha",

And the mocha options (mocha.opts) looks like below.

test/setup.ts
--compilers ts:ts-node/register
--compilers tsx:ts-node/register
./src/**/*.spec.ts
like image 455
Raathigesh Avatar asked Jun 24 '16 15:06

Raathigesh


2 Answers

ts-mock-imports gives you run time control over your imports and maintains type safety.

in app.spec.ts

import * as httpModule from 'http';
import { App } from '../src/app';
import { ImportMock } from 'ts-mock-imports';

const httpMock = ImportMock.mockClass(httpModule, 'Http');

const app = new App(); // App now uses a fake version of the Http class

Now you can control how the Http module behaves in your tests.

Mock the response to a get:

httpMock.mock('get', { data: true });

const response = app.makeGetRequest(); // returns { data: true }
like image 169
EmandM Avatar answered Sep 28 '22 01:09

EmandM


The import statement in typescript is compiled to require. You can use proxyquire to mock any dependencies in your tests

like image 28
BillyTom Avatar answered Sep 28 '22 01:09

BillyTom