简体   繁体   中英

jest test cannot import cesium using create react app and craco

I am using create react app with craco, and craco-cesium to load cesium into my project. I am trying to setup jest to start creating tests but the issue is Cesium is using requireJS.

I added the following to my package.json

  // package.json

  ...
  "jest": {
    "collectCoverageFrom": [
      "src/**/*.{js,jsx,ts,tsx}', '!src/**/*.d.ts"
    ],

    "globalSetup": "<rootDir>/setupTests.js"
  }
  ...

based on the ticket opened up here: https://github.com/facebook/jest/issues/1914

I setup the setupTests.js with the following code:

// setupTests.js
module.exports = async () => {
  var cesium = require('cesium');
  process.$Cesium = cesium
};

and I have the first basic test for valid rendering:

// App.test.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});

however I get the error in one of my view inside <App /> component with the following code:

import Cesium from "cesium";
...
TypeError: Cannot read property 'Ion' of undefined
...
Cesium.Ion.defaultAccessToken = '...';

reporting Cesium as undefined when calling it's functions. I tried to use jest.config.js for jest to pick up the configuration from there with the following code:

// jest.config.js
const { createJestConfig } = require("@craco/craco");

const cracoConfig = require("../craco.config.js");
const jestConfig = createJestConfig(cracoConfig);

module.exports = jestConfig;

but create react app doesn't pick up this file so I cannot try this to verify if this would work.

encoutered the same problem.

Upgrading react-scripts to version 4.0.1 and @craco/craco@ to version 6.0.0, seemed to solve these problems, and jest now recognizes all imports from cesium. No other configuration files were needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM