【问题标题】:Using babel-plugin-rewire to test private non-referenced functions使用 babel-plugin-rewire 测试私有非引用函数
【发布时间】:2019-11-22 22:23:59
【问题描述】:

我在 main.test.js 中使用 babel-plugin-rewire (https://www.npmjs.com/package/babel-plugin-rewire) 来测试 main.js 中的非导出函数。除了在 main.js 中未引用该函数的情况外,这一直有效;在这种情况下,我收到以下错误:TypeError: _get__(...) is not a function。

只有在 main.js 中添加对函数的引用后,我才能在测试文件中访问它(即使我实际上没有调用该函数,它也可以工作)。但是我不想对 main.js 进行任何更改。这是 babel-plugin-rewire 的预期行为吗?是否有解决方法?

//main.js
function test123() {
    return true;
}
test123; //Cannot access function in test file unless I add this reference!

//main.test.js
const test123 = require('./main').__get__('test123');

test('test123', () => {
  expect(test123()).toEqual(true);
});

【问题讨论】:

    标签: javascript jestjs babeljs babel-jest


    【解决方案1】:

    您可以在 main.js 中测试非导出函数,但非导出函数需要在同一个文件中的至少一个导出函数中使用。

    在你的情况下,这将在没有参考的情况下工作。

    //main.js
    export default function foo() {
       test123();
    }
    function test123() {
        return true;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-19
      • 2019-01-29
      • 2018-08-21
      • 1970-01-01
      • 2019-06-21
      相关资源
      最近更新 更多