【问题标题】:React Jest - import JS module without using require/exportReact Jest - 在不使用 require/export 的情况下导入 JS 模块
【发布时间】:2017-09-27 02:14:00
【问题描述】:

是否可以在不使用 require/export 的情况下使用 Jest 测试单个 JavaScript 文件?

假设我想测试 abc.js。这是 abc.js 的一个例子:

(function(){
   return {
       foo: function(){}
   }
})();

现在假设我的测试文件是 abc.test.js。我想测试 foo 是否是一个函数。如果不使用 abc.js 中的 modules.exports 和 abc.test.js 中的 require,我将如何继续测试这个文件?

提前致谢

【问题讨论】:

  • 如果不在 Jest 加载底层源文件之前转换它,这看起来是不可能的。您不使用导出有什么原因吗?
  • 我不想为我的源文件包含测试代码。我想我将不得不使用 grunt 或其他东西将其删除以进行生产

标签: unit-testing reactjs jestjs commonjs separation-of-concerns


【解决方案1】:

使用命名函数、try/catch 块和内联断言来使用普通 Node.js 对其进行测试:

const assert = require('assert');

(function hi(){
  hi.foo = Function;
  try
    {
    assert.ok(typeof hi.foo === 'function', 'Not a function');
    assert.ok(typeof hi.foo === 'string', 'Not a string');
    }
  catch(e)
    {
    console.log(e.message);
    }
  }
)();

然后运行它:

node foo.js

注释掉面向测试的代码以避免将其包含在源文件中:

/*const assert = require('assert');*/

(function hi(){
  hi.foo = Function;
  /*
  try
    {
    assert.ok(typeof hi.foo === 'function', 'Not a function');
    assert.ok(typeof hi.foo === 'string', 'Not a string');
    }
  catch(e)
    {
    console.log(e.message);
    }
  */
  }
)();

然后以编程方式删除 cmets 并将输出通过管道传输到 *nix shell 中的节点:

cat foo.js | tr -d '/*' | node

或 Powershell:

$string = cat foo.js
$string.Split("/*") | node

并在构建过程中使用 Grunt 或其他工具去除注释块。

参考文献

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 2017-11-05
    • 1970-01-01
    • 2020-08-26
    • 2016-07-12
    • 2013-08-22
    • 2014-11-14
    • 1970-01-01
    • 2014-03-16
    相关资源
    最近更新 更多