🔥 ArcGIS JS API can't be used in Jest unit tests

799
4
Jump to solution
11-16-2023 10:47 AM
RussellMGreen
New Contributor II

Trying to use the ArcGIS JS API in a unit test in Jest results in an import error:

RussellMGreen_0-1700155349874.png

Environment:

OS: Windows 10

Node: v20.1.0

Setup: nx repo > library > jest unit test

This issue can be found by simply creating a new NX monorepo/project and creating a TypeScript library and trying to use any ArcGIS JS API class within a Jest spec file (unit test).

Example:

`my-test.spec.ts`

// This import will fail!
import { Point } from '@arcgis/core/geometry';

describe('my test', ()=>{
  it('will fail', ()=>{
    new Point({ latitude: 42, longitude: -72 });
  });
});

 

Steps to Reproduce:

  1. git clone https://github.com/rustygreen/arcgis-js-api-issue-example.git
  2. cd arcgis-js-api-issue-example
  3. npm install
  4. npm run test -- arcgis-angular
  5. 🔥 test will fail with import error

 

0 Kudos
1 Solution

Accepted Solutions
AndyGup
Esri Regular Contributor

Ah okay, I clearly didn't look deep enough. Yep, that ignore pattern isn't working correctly. This isn't a problem with "@arcgis/core". The error "Cannot use import statement outside a module" is a well known JavaScript configuration issue.

I changed this in your app and it worked:

    "transformIgnorePatterns": [
      "node_modules/(?!(@angular|@arcgis|@esri|@stencil|@popperjs)/)"
    ],

 

jest-test.png

 

View solution in original post

4 Replies
AndyGup
Esri Regular Contributor

It's been a while since I used Jest with Angular and no guarantee that it will work, but you may need to do something like this in your Jest config:

"transformIgnorePatterns": [
   "node_modules/(?!(@angular|@arcgis|@esri|@stencil/)"
],

And, you might also need: https://www.npmjs.com/package/jest-preset-angular.

0 Kudos
RussellMGreen
New Contributor II

The current Jest config in the sample repo should already be handling this dynamically (unless I'm missing something):

arcgis-js-api-issue-example/libs/arcgis-angular/jest.config.ts at main · rustygreen/arcgis-js-api-is...

RussellMGreen_0-1700169020037.png

Also, just to note; you can take Angular out of this mix and the same issue will occur. I just happened to create the library as an Angular library using the NX cli.

0 Kudos
AndyGup
Esri Regular Contributor

Ah okay, I clearly didn't look deep enough. Yep, that ignore pattern isn't working correctly. This isn't a problem with "@arcgis/core". The error "Cannot use import statement outside a module" is a well known JavaScript configuration issue.

I changed this in your app and it worked:

    "transformIgnorePatterns": [
      "node_modules/(?!(@angular|@arcgis|@esri|@stencil|@popperjs)/)"
    ],

 

jest-test.png

 

RussellMGreen
New Contributor II

Yep, that solved it. Thanks, @AndyGup!

0 Kudos