TypeError: mxgraph is not a function when running Jest unit tests
P粉953231781
P粉953231781 2024-02-21 15:53:26
0
1
416

I have a Vue JS component using the mxgraph package: https://www.npmjs.com/package/mxgraph

and import it like this:

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';

This is my 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"
    }
  }
};

When I run the test I get:

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)

When I run my app with a normal webpack profile, the imports work fine. Is there anything I need to add to jest.config to fix this error?

P粉953231781
P粉953231781

reply all(1)
P粉407936281

mxGraph The npm package has always been a mess.

Please note that mxGraph's successor maxGraph will handle it: https://github.com/maxGraph/maxGraph

Since you are using Vue and your code snippet indicates that you are using TypeScript, I recommend using https://github.com/typed-mxgraph/typed-mxgraph. You get a complete working solution with TypeScript types and mxGraph npm integration. The readme file provides comprehensive usage examples and demonstrations. When using mxGraph in a jest test, depending on which part of mxGraph you are running, you will need to use the jsdom environment in the relevant test. This is because mxGraph uses the window object, which is not available in the node environment.

If you still want to keep the js way of mxGraph integration, you can check https://github.com/jgraph/mxgraph/issues/175#issuecomment-482008896 or other stack overflow issues (there are many of them ).

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!