Search code examples
reactjsjestjsts-jest

Jest fails with 'self is not defined' when importing react-diagrams


Im trying to create a basic jest test interacting with a npm dependency: react-diagrams

The failing test

import { DiagramModel } from '@projectstorm/react-diagrams'

test('importing react diagrams', () => {
    let x = DiagramModel
});

Simply referencing the DiagramModel class causes this error:

    ReferenceError: self is not defined

    > 1 | import { DiagramModel } from '@projectstorm/react-diagrams'
        | ^
      2 |
      3 | test('importing react diagrams', () => {
      4 |     let x = DiagramModel

      at Object.<anonymous> (node_modules/@projectstorm/react-diagrams/dist/index.umd.js:1:331)
      at Object.<anonymous> (tests/DiagramModel.test.ts:1:1)

Other tests works fine, and the dependency works fine when bundeled elsewhere.

jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};

package.json

"jest": "^26.6.3",
"ts-jest": "^26.5.2",
...

Any ideas what I can do to remedy this?

Reproducing

Added test + configuration in a codesandbox (but could not get the test runner to pick it up). The full repo


Solution

  • After some tests it finally works with this configuration :

    jest.config.js

    module.exports = {
      preset: 'ts-jest',
      testEnvironment: 'jsdom',
    };
    

    package.json :

    {
      "name": "jest-test",
      "version": "1.0.0",
      "main": "index.js",
      "license": "MIT",
      "devDependencies": {
        "jest": "^26.6.3",
        "ts-jest": "^26.5.2"
      },
      "scripts": {
        "test": "jest"
      },
      "dependencies": {
        "@emotion/react": "^11.1.5",
        "@emotion/styled": "^11.3.0",
        "@projectstorm/react-canvas-core": "^6.5.2",
        "@projectstorm/react-diagrams": "^6.5.2",
        "@projectstorm/react-diagrams-routing": "^6.5.2",
        "closest": "^0.0.1",
        "dagre": "^0.8.5",
        "pathfinding": "^0.4.18",
        "paths-js": "^0.4.11",
        "react": "^17.0.2",
        "resize-observer-polyfill": "^1.5.1"
      }
    }
    

    You were missing the fact that @projectstorm/react-diagrams is a react library and it needs dom environment not nodejs.