node.jstypescriptunit-testingmocha.jsproxyquire

proxyquire not stubbing static methods - nodejs


i have two classes ValidationHelper, BeneficiaryHelper with a static method each which i am trying to mock using proxyquire but on running npm test its giving me error:

TypeError: Cannot read property 'checkMandatory' of undefined

typescript file code:

import { ValidationHelper } from '../validations/common';
import { BeneficiaryHelper } from '../validations/beneficiary';
const lib = nbind.init<typeof LibTypes>(__dirname + '/../../').lib;



class beneficiaryaddv2 {

    utilities: any = {};

    constructor() {
        this.utilities = new lib.Utilities();
    }


    parse(req: any, res: any, message: { [k: string]: any }) {

        //..more code

        ValidationHelper.checkMandatory(req.body.beneficiaryType, 'beneficiaryType');
        ValidationHelper.checkMandatory(req.body.customerId, 'customerId');
        BeneficiaryHelper.checkBeneficiaryType(req.body.beneficiaryType);

        message.RESERVED1 = req.body.city;
        //..more code
    }

}

export { beneficiaryaddv2 }

code for unit test of this file:

    class BeneficiaryHelper {
    static checkBeneficiaryType(beneficiaryType: string) { return; }
}

    class ValidationHelper {
        static checkMandatory(stringValue: string, parameterName: string, errorMessage: string = '') { return; }
    }


describe('unit test for beneficiary add parse', () => {

let utilBase;
let utilGenerateRRNMock;
let utilGenerateSTANMock;

let target = common.proxyquire('../../APIServer/controller/beneficiaryaddv2', {
    'nbind': common.nbindStub,
    '../../local_modules/logger': common.LoggerMock,
    '../validations/common': ValidationHelper,
    '../../local_modules/dbconnmgr': common.DbConnMgrMock,
    '../validations/beneficiary': BeneficiaryHelper,
    '@noCalThrough': true
});

//...

});

Solution

  • Hope this works (y)!!!

    let ValidationHelperMock = {
      ValidationHelper: class{
        static checkMandatory(stringValue, parameterName, errorMessage){ };
      }
    };
    
    let BeneficiaryHelperMock = {
      BeneficiaryHelper: class{
        static checkBeneficiaryType(beneficiaryType){ };
      }
    };
    
    describe('unit test for beneficiary add parse', () => {
    
    let utilBase;
    let utilGenerateRRNMock;
    let utilGenerateSTANMock;
    
    let target = common.proxyquire('../../APIServer/controller/beneficiaryaddv2', {
        'nbind': common.nbindStub,
        '../../local_modules/logger': common.LoggerMock,
        '../validations/common': ValidationHelperMock,   //check these paths to exact from the test file
        '../../local_modules/dbconnmgr': common.DbConnMgrMock,
        '../validations/beneficiary': BeneficiaryHelperMock,   //check these paths to exact from the test file
        '@noCalThrough': true
    });
    
    //...
    
    });