【问题标题】:TypeError: mxgraph is not a function When Running Jest Unit TestsTypeError:运行 Jest 单元测试时,mxgraph 不是函数
【发布时间】:2021-12-14 19:59:21
【问题描述】:

我有一个使用 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 中添加什么来修复此错误吗?

【问题讨论】:

    标签: javascript vue.js webpack jestjs mxgraph


    【解决方案1】:

    mxGraph npm 包一直都是一团糟。

    请注意,mxGraph 的继任者 maxGraph 将处理它:https://github.com/maxGraph/maxGraph

    由于您使用的是 Vue 并且您的 sn-p 表明您正在使用 TypeScript,我建议您使用 https://github.com/typed-mxgraph/typed-mxgraph。您将获得 TypeScript 类型和用于 mxGraph npm 集成的完整工作解决方案。自述文件提供了全面的使用示例和演示。 在 jest 测试中使用 mxGraph 时,根据您正在运行的 mxGraph 部件,您将需要在相关测试中使用jsdom environment。这是因为 mxGraph 使用 window 对象,而 node 环境不提供该对象。

    如果您仍想保留 js 方式进行 mxGraph 集成,您可以查看 https://github.com/jgraph/mxgraph/issues/175#issuecomment-482008896 或其他堆栈溢出问题(它们很多)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      • 2020-02-09
      • 2019-05-16
      相关资源
      最近更新 更多