proxyquire不存根静态方法-Node.js

时间:2019-03-28 05:11:09

标签: node.js typescript unit-testing mocha proxyquire

我有两个类ValidationHelper,BeneficiaryHelper和一个静态方法,每个类我都试图使用proxyquire进行模拟,但是在运行npm时测试了它给我的错误:

TypeError:无法读取未定义的属性“ checkMandatory”

打字稿文件代码:

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 }

此文件的单元测试代码:

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

//...

});

1 个答案:

答案 0 :(得分:1)

希望这行得通(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
});

//...

});