'How To Mock a Dependency Class in Typescript Node Using Chai-Spies

Given something like my-module.ts that will be called by an external consumer that of course cannot do dependency injection to this module's constructor:

import Dependency from 'dependency-class';
import {myDataFormat} from '../types/my-module-types';

export default class MyModule {
    private dependency: Dependency;

    constructor() {
        this.dependency = new Dependency();
    }

    getMyData(): myDataFormat {
        const dependencyData = this.dependency.getDependencyData();
        // parse/process data
        // return modified data 
    }

}

How can we test that Dependency.getDependencyData() was called by MyModule.getMyData()... using only mocha, chai, and chai-spies?



Solution 1:[1]

my-module.test.ts:

import Dependency from 'dependency';
import MyModule from '../src/modules/my-module'

import 'mocha';

import chai = require('chai');
chai.should(); //enable chai should()

import spies = require('chai-spies');
chai.use(spies); //extend chai with spies plugin



describe('Tests.MyModule', () => {

    let instance: MyModule | undefined;

    before(() => {
        // Create spies/stubs/mocks as needed
        chai.spy.on(Dependency.prototype, ['getDependencyData'], () => {
            // this is replacement function body if we want to test specific return data
        });

        // Create MyModule instance
        instance = new MyModule();
    });

    after(() => {
        // Reset MyModule instance
        instance = undefined;

        // Remove spies/stubs/mocks that were created
        chai.spy.restore();
    });


    describe('getMyData()', () => {
        it('should call Dependency.getDependencyData()', () => {
                // Arrange
                // - Set up spies/stubs/mocks (done above)
                // - Create a MyModule instance (done above)

                // Act
                instance.getMyData();

                // Assert
                Dependency.prototype.getDependencyData.should.have.been.called();
        });
    });
});


Versions in Node package.json:

"@types/chai": "^4.3.0",
"@types/chai-spies": "^1.0.3",
"@types/mocha": "^9.1.0",
"chai": "^4.3.6",
"chai-spies": "^1.0.0",
"mocha": "^9.2.1",

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1