如何使用 Chai-Spies 在 Typescript 节点中模拟依赖项 Class

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

给定类似 my-module.ts 的东西将由外部消费者调用,当然不能对该模块的构造函数进行依赖注入:

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 
    }

}

我们如何测试 Dependency.getDependencyData() 是由 MyModule.getMyData()... 仅使用 mocha, chai, and chai-spies 调用的?

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();
        });
    });
});


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",