Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing React Jest-不使用require/export导入JS模块_Unit Testing_Reactjs_Jestjs_Commonjs_Separation Of Concerns - Fatal编程技术网

Unit testing React Jest-不使用require/export导入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,我将如何继续测试此文件 提前感谢使用命名函数、

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

假设我想测试abc.js。下面是abc.js的一个示例:

(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或其他工具在构建过程中删除注释块

参考资料


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