I have a mapbox.service.ts
import * as mapboxgl from 'mapbox-gl';
In this service I just create this mapbox map
this.map = new mapboxgl.Map({
accessToken: this.accessToken,
container: 'mapbox-container',
style: 'mapbox://styles/mapbox/streets-v12',
center: { lat: 43.238949, lng: 76.889709 },
zoom: this.currentZoom,
});
Application works fine. However, when I run jest unit tests, this mapbox.service.spec.ts fails.
ReferenceError: TextDecoder is not defined
1 | import { Injectable } from '@angular/core';
> 2 | import * as mapboxgl from 'mapbox-gl';
Inside mapbox.service.spec.ts I did not add any test cases.
import { inject, TestBed } from '@angular/core/testing';
import { MapboxService } from './mapbox.service';
describe('Service: Mapbox', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [MapboxService],
});
});
it('should ...', inject([MapboxService], (service: MapboxService) => {
expect(service).toBeTruthy();
}));
});
Why TextDecoder is not defined?
I changed my setup.jest.ts file to
import 'jest-preset-angular/setup-jest';
import { TextEncoder } from 'node:util';
global.TextEncoder = TextEncoder;
On the Internet I found this solution, then I tried it, but it shows other errors:
Test suite failed to run
src/setup.jest.ts:2:29 - error TS2307: Cannot find module 'node:util' or its corresponding type declarations.
2 import { TextEncoder } from 'node:util';
~~~~~~~~~~~
src/setup.jest.ts:4:1 - error TS2304: Cannot find name 'global'.
4 global.TextEncoder = TextEncoder;
I'm just using a regular MapBox map, nothing special. Anyone using Mapbox in their application, how to fix this unit test failure?
I understood why the error occurs. This is because the Node version and the mapbox-gl versions are not compatible with each other.
I downgraded my Node version, but the error still persists. My node version is v20 downgraded to (v18, v16, v14).
I did not touch Node version and then started downgrading mapbox-gl version. My current version of mapbox-gl is v3.1.2., then I downgraded it until the error message disappeared. So, when mapbox-gl version became v2.15.0, then the error went away.
Now, everything works fine, it may be helpful for those who may face the same problem in the future :)