非导出函数的 Mocha 单元测试 returns 'xx is not a function'

Mocha unit test on a non exported function returns 'xx is not a function'

我正在尝试 运行 使用 mocha 对非导出函数进行单元测试,但出现错误 'xx is not a function'。示例结构就像 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。尝试通过如下集成对其进行测试

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