首頁  >  問答  >  主體

類型錯誤:執行 Jest 單元測試時 mxgraph 不是函數

我有一個使用 mxgraph 套件的 Vue JS 元件: https://www.npmjs.com/package/mxgraph

並像這樣導入它:

import * as mxgraph from 'mxgraph';

const {
  mxClient,
  mxStackLayout,
  mxGraph,
  mxRubberband,
  mxUtils,
  mxFastOrganicLayout,
  mxSwimlaneLayout,
  mxEvent,
  mxGraphModel,
  mxConstants,
  mxHierarchicalLayout,
  mxSwimlaneManager
} = mxgraph();
// noinspection TypeScriptCheckImport
import {
  mxConstants as MxConstants
} from 'mxgraph/javascript/mxClient.js'
import axios from 'axios';

這是我的 jest.config.js

module.exports = {
  preset: "@vue/cli-plugin-unit-jest/presets/no-babel",
  moduleFileExtensions: ["js", "ts", "json", "vue"],
  transform: {
    ".*\.(vue)$": "vue-jest",
    "^.+\.tsx?$": "ts-jest"
  },
  globals: {
    "ts-jest": {
      tsConfig: "src/tsconfig.json"
    }
  }
};

當我執行測試時,我得到:

TypeError: mxgraph is not a function

  20 |   import * as mxgraph from 'mxgraph';
  21 | 
> 22 |   const {
     | ^
  23 |     mxClient,
  24 |     mxStackLayout,
  25 |     mxGraph,

  at src/components/task/job/job_pipeline_mxgraph.vue:22:1
  at Object.<anonymous> (src/components/task/job/job_pipeline_mxgraph.vue:568:3)
  at src/components/task/job/task_template_wizard_creation/step_attach_directories_task_template.vue:67:1
  at Object.<anonymous> (src/components/task/job/task_template_wizard_creation/step_attach_directories_task_template.vue:367:3)
  at Object.<anonymous> (tests/unit/task/job/task_template_wizard_creation/step_attach_directories_task_template.spec.js:3:1)

當我使用普通的 webpack 設定檔來執行我的應用程式時,導入工作正常。我需要在 jest.config 中添加任何內容來修復此錯誤嗎? ###
P粉953231781P粉953231781241 天前409

全部回覆(1)我來回復

  • P粉407936281

    P粉4079362812024-02-22 00:15:04

    mxGraph npm 套件一直都是一團糟。

    請注意,mxGraph 的後繼者 maxGraph 將處理它: https://github.com/maxGraph/maxGraph

    #由於您正在使用 Vue 並且您的程式碼片段表明您正在使用 TypeScript,因此我建議您使用 https://github.com/typed-mxgraph/typed-mxgraph。您將獲得 TypeScript 類型和 mxGraph npm 整合的完整工作解決方案。自述文件提供了全面的使用範例和演示。 在 jest 測試中使用 mxGraph 時,根據您正在執行的 mxGraph 部分,您將需要使用 相關測試中的jsdom環境。這是因為 mxGraph 使用 window 對象,該對像在 node 環境中不可用。

    如果您仍然想保留mxGraph 整合的js 方式,可以查看https://github.com/jgraph/mxgraph/issues/175#issuecomment-482008896 或其他堆疊溢位問題(它們很多)。

    回覆
    0
  • 取消回覆