【问题标题】:How to fix "SVG Not defined" in JEST unit testing如何在 JEST 单元测试中修复“SVG 未定义”
【发布时间】:2019-05-30 22:33:52
【问题描述】:

我正在尝试为 typescript 类中定义的函数设置单元测试用例。这个类依赖于 svg.js。 现在,当我尝试用 jest 对函数进行单元测试时,它会引发错误 SVG.extend 或 SVG 不是函数。

我们已经尝试在 jest.config.js 文件中让 testEnvironment 成为 jsdom 的节点。

ts的代码如下 从'svg.js'导入SVG;

export class DrawManager {
  private static _drawingStage : SVG.Nested|undefined;
  private static _canvas : SVG.Doc|undefined;
}

static start(div: string) {
    this._canvas = SVG(div)
    this._drawingStage = this._canvas.nested();
}

单元测试代码如下

import { DrawManager } from './drawmanager';
describe('Test for Draw Manager', () => {
    it('should process task loader method', () => {
    DrawManager.start('drawing');
 });
});

我们期望输出通过测试用例而没有任何 SVG 依赖问题,并使用已启动的 svg 类运行测试用例

我们将不胜感激

【问题讨论】:

    标签: typescript unit-testing webpack jestjs svg.js


    【解决方案1】:

    我找到了解决方案。您需要做的是为 jest 创建一个 setupFile。 以 setupJestMock.ts 为例

    有了这个内容:

    const obj = require('@svgdotjs/svg.js');
    const SVG = (arg) => {
      return obj.SVG(arg)
    };
    
    Object.assign(SVG, obj);
    
    (global as any).SVG = SVG;
    
    

    然后将它添加到您的 jest 配置中,无论是在 package.json 中还是您配置 jest 的任何方式:

    我的 jest.config.json 中有它

    "setupFiles": [
        "<rootDir>/setupJestMock.ts"
      ],
    

    【讨论】:

      猜你喜欢
      • 2019-09-27
      • 2021-06-12
      • 2020-02-11
      • 2022-06-30
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 2021-04-24
      • 1970-01-01
      相关资源
      最近更新 更多