Unit testing React Jest-不使用require/export导入JS模块
是否可以使用Jest测试单个JavaScript文件而不使用require/export 假设我想测试abc.js。下面是abc.js的一个示例:Unit testing React Jest-不使用require/export导入JS模块,unit-testing,reactjs,jestjs,commonjs,separation-of-concerns,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,我将如何继续测试此文件 提前感谢使用命名函数、
(function(){
return {
foo: function(){}
}
})();
现在让我们假设我的测试文件是abc.test.js。我想测试foo是否是一个函数。如果不使用abc.js中的modules.exports和abc.test.js中的require,我将如何继续测试此文件
提前感谢使用命名函数、try/catch块和内联断言使用plain 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或其他工具在构建过程中删除注释块
参考资料