使用jest在节点的公共文件夹中测试javascript

问题描述 投票:0回答:2

我在放置在 Node js 公共目录中的 example.js 文件中有一个简单的 javascript 函数。
我正在使用 jest 进行单元测试。
问题是如果我在 public 文件夹中的 example.js javascript 文件中写入以下内容:
module.exports.myFunction = myFunction;
Jest 测试文件能够使用 require() 导入它并执行测试,但是当我运行 Web 应用程序时,当我为包含此 javascript 的页面提供服务时,浏览器会抱怨: 未捕获的引用错误:模块未定义

测试节点应用程序公共目录中的javascript文件的正确方法是什么?
在项目中使用导出和/或导入会报告无法识别并导致错误。

这是如何做到的?

javascript jestjs public
2个回答
1
投票

正如评论中提到的

require(...)
module.exports
Common JS Modules 相关,NodeJS 运行时原生支持它们,但浏览器不支持。因此基本上您需要添加额外的构建配置以使您的模块在两个运行时中工作。

如果您想在 CommonJs 和浏览器友好的捆绑包中都有输出 - 您可以在 ES Modules 中编写所有代码,并使用 webpack 等构建工具来提供不同格式的输出。

此外,从 Node 13.2.0 开始 - 它原生支持 ES 模块。所以无论如何我都会坚持使用 ES 模块进行持续开发。

另请查看这篇短文,了解主要 JS 模块格式差异。


0
投票

几个月前我不得不处理这个问题,当时我无法找到准确的答案,但我确实明白这个问题是由于我们运行代码和测试代码的环境不同造成的。当时我无法使用额外的工具来解决问题,所以我为自己创建了这个解决方法,这不是最好的,但很有效。

// Include this at the top of the public js file
if (typeof __funcs == 'undefined' || typeof __funcs != 'object') {
    var __funcs = {};
}

function one() {}

function two() {
    __funcs.one();
}

// Include this at the bottom of the public js file
try {
    if (typeof module != 'undefined') {
        // include the functions in here you want to export and test using  
        // Jest in Node env in an isolated manner
        module.exports = __funcs = {
            ...__funcs, one, two 
        };
    } else {
        // include functions in here for situations when you want to test 
        // calls to some other function  
        __funcs = { ...__funcs, one };
    }
} catch (ex) {
    console.error(`Error while exporting entities from [name of the file] script`, ex);
}

一些要点:

  1. 双下划线用于指示目的。它是一种命名约定,表明该变量是敏感/内部的,应谨慎使用或访问,并防止意外更改或覆盖。

  2. 我觉得这里使用 var 是不可避免的,因此增加了这种方法的负面影响。

  3. 我认为你可以通过设计一种方法来设置内部命名机制来摆脱 var ,其中你想要为其编写测试用例的每个公共 js 文件都有自己单独的 __funcs 版本。然而,这会使您编写测试用例变得复杂,其中调用单独文件中的函数。这就是我怀疑我使用 var 的全部原因以及我们在文件顶部包含的代码的目的。我认为 __funcs 不应该被覆盖,我们不必为每个文件声明单独的变量,__funcs 将是通用的。

© www.soinside.com 2019 - 2024. All rights reserved.