【问题标题】:Mocha unit test on a non exported function returns 'xx is not a function'非导出函数的 Mocha 单元测试返回“xx 不是函数”
【发布时间】:2020-11-29 03:53:50
【问题描述】:

我正在尝试使用 mocha 对非导出函数运行单元测试,但它给出了错误“xx 不是函数”。示例结构类似于 ff 代码,我想在其中测试函数 isParamValid。 settings.js中的代码格式已经存在于我们的系统中,所以我无法重构它。

// settings.js
const settings = (() => {
  const isParamValid = (a, b) => {
    // process here
  }

  const getSettings = (paramA, paramB) => {
    isParamValid(paramA, paramB);
  }
  
  return {
    getSettings,
  }
})();

module.exports = settings;

我试过ff代码来测试,但是mocha报错ReferenceError: isParamValid is not defined

// settings.test.js
const settings= rewire('./settings.js');
describe('isParamValid', () => {
    it('should validate param', () => {
      let demo = settings.__get__('isParamValid');

      expect(demo(0, 1)).to.equal(true);
      expect(demo(1, 0)).to.equal(true);
      expect(demo(1, 1)).to.equal(false);
    })
  })

【问题讨论】:

  • 不,你不能直接测试isParamValid。因为这里是私人的。

标签: javascript unit-testing mocha.js chai rewire


【解决方案1】:

您无法在此处直接访问isParamValid。尝试通过以下集成对其进行测试

const settings = require('./settings.js'); // No need of rewire

describe('isParamValid', () => {
    it('should validate param', () => {
      const demo = settings.getSettings; // Read it from getSettings

      expect(demo(0, 1)).to.equal(true);
      expect(demo(1, 0)).to.equal(true);
      expect(demo(1, 1)).to.equal(false);
    })
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-04
    • 2011-02-06
    • 1970-01-01
    • 2015-07-25
    • 1970-01-01
    相关资源
    最近更新 更多