Mapbox, Angular, jest unit test fails

Discussão em 'Angular' iniciado por Maksat Madeniyetov, Janeiro 18, 2025.

  1. 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?

    Continue reading...

Compartilhe esta Página