React Jest - 导入JS模块而不使用require / export

时间:2017-04-28 21:19:17

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

是否可以使用Jest测试单个JavaScript文件而不使用require / export?

假设我想测试abc.js.以下是abc.js的示例:

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

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

提前致谢

1 个答案:

答案 0 :(得分:0)

使用命名函数,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);
    }
  */
  }
)();

然后以编程方式删除注释并将输出传递给* nix shell中的节点:

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

或Powershell:

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

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

<强>参考