【问题标题】:jest test with xmljs GLOBAL not defined未定义 xmljs GLOBAL 的玩笑测试
【发布时间】:2020-08-22 08:51:23
【问题描述】:

目前我正在使用

编写一个应用程序
  • NodeJS v13.12.0
  • 开玩笑 25.4.0
  • xmljs0.3.2
  • 打字稿 3.8.3
  • ts-jest 25.4.0

此应用程序应模仿 CalDAV 服务器。出于这个原因,我依赖于模块 xmljs,它是(在我的研究之后)唯一给我一个直接的path 方法来在 XML 中查找属性的模块。

在 node Container 中,App 运行良好,没有任何错误。但是当我用 Jest 开始测试时,测试失败并出现错误

ReferenceError: GLOBAL is not defined
      at node_modules/xmljs/core.js:46:2
      at Object.<anonymous> (node_modules/xmljs/core.js:176:3)
      at node_modules/xmljs/XmlParser.js:3:11
      at Object.<anonymous> (node_modules/xmljs/XmlParser.js:204:3) 

我现在知道,这个错误源于 xmljs 模块试图设置 GLOBAL 变量,在 NodeJS 中该变量解析为 global。但这并不是开玩笑的。

我的代码如下:

import XmlParser = require("xmljs");

/*
* data is the body of a PROPFIND request
*/
new XmlParser({ strict: true }).parseString(data, (err, xmlNode) => {
    // omit err
    xmlNode.path(["propfind", "prop"], true);

    const propertiesObj: XmlNode[] = childs[0].children;
    const properties: string[] = [];

    Object.keys(propertiesObj).forEach(n => {
        properties.push(n);
    });

    logger.silly("Returning properties: %O", properties);
});

任何人都可以

  1. 向我展示一个无需大量修改代码即可使用的模块

    • 支持纯js实现,不使用node-gyp(因为可以在windows server上使用)
  2. 告诉我如何解决这个问题,以欺骗在 xmljs 中设置的这个 GLOBAL 变量

感谢您的帮助

【问题讨论】:

    标签: node.js typescript jestjs ts-jest


    【解决方案1】:

    您可以在测试设置中设置GLOBAL 的值。 GLOBAL 变量似乎是节点中 global 的弃用形式。

    在您的jest.config.js 文件中,您可以通过setupFiles 选项添加安装文件:

    module.exports = {
        [...] // Other configurations
        setupFiles: ['<rootDir>/define-deprecated-global.js']
    };
    

    在文件define-deprecated-global 中,您可以将GLOBAL 变量定义为:

    global.GLOBAL = global;
    

    【讨论】:

    • 谢谢。我尝试使用 beforeAll 钩子。但是这个没有用。这种方法现在终于奏效了。谢谢!
    猜你喜欢
    • 2017-11-01
    • 2018-06-02
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    • 2022-12-05
    • 2021-06-25
    • 1970-01-01
    相关资源
    最近更新 更多