簡體   English   中英

如何在 JEST 單元測試中修復“未定義 SVG”

[英]How to fix "SVG Not defined" in JEST unit testing

我正在嘗試為 typescript 類中定義的函數設置單元測試用例。 這個類依賴於 svg.js。 現在,當我嘗試使用 jest 對函數進行單元測試時,它會拋出錯誤 SVG.extend 或 SVG is not a function。

我們已經在 jest.config.js 文件中嘗試了讓 testEnvironment 成為節點到 jsdom 的方法。

ts 的代碼如下 import SVG from 'svg.js';

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 類運行測試用例

幫助將不勝感激

我找到了解決方案。 您需要做的是為 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;

然后在 package.json 或任何配置 jest 的方式中將它添加到你的 jest 配置中:

我在 jest.config.json 中有它

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM