From c0af6c32a936d5ee590435f883653cbfb38aa65a Mon Sep 17 00:00:00 2001 From: ahnpnl Date: Wed, 19 Jun 2024 21:50:15 +0200 Subject: [PATCH] feat: add polyfill for TextEncoder fixes #1914 fixes #2514 --- setup-jest.js | 7 +++++++ setup-jest.mjs | 6 ++++++ src/config/setup-jest.spec.ts | 13 +++++++++++++ 3 files changed, 26 insertions(+) diff --git a/setup-jest.js b/setup-jest.js index 991216ea61..684d8b7bf2 100644 --- a/setup-jest.js +++ b/setup-jest.js @@ -1,11 +1,18 @@ require('zone.js'); require('zone.js/testing'); +const { TextEncoder, TextDecoder } = require('util'); + const { getTestBed } = require('@angular/core/testing'); const { BrowserDynamicTestingModule, platformBrowserDynamicTesting, } = require('@angular/platform-browser-dynamic/testing'); +if (typeof globalThis.TextEncoder === 'undefined') { + globalThis.TextEncoder = TextEncoder; + globalThis.TextDecoder = TextDecoder; +} + const testEnvironmentOptions = globalThis.ngJest?.testEnvironmentOptions ?? Object.create(null); getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), testEnvironmentOptions); diff --git a/setup-jest.mjs b/setup-jest.mjs index 63247e4597..8ff1a7c2d0 100644 --- a/setup-jest.mjs +++ b/setup-jest.mjs @@ -2,6 +2,12 @@ import 'zone.js'; import 'zone.js/testing'; import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing'; +import { TextEncoder, TextDecoder } from 'util'; + +if (typeof globalThis.TextEncoder === 'undefined') { + globalThis.TextEncoder = TextEncoder; + globalThis.TextDecoder = TextDecoder; +} const testEnvironmentOptions = globalThis.ngJest?.testEnvironmentOptions ?? Object.create(null); diff --git a/src/config/setup-jest.spec.ts b/src/config/setup-jest.spec.ts index 754cf77c40..18f1811dee 100644 --- a/src/config/setup-jest.spec.ts +++ b/src/config/setup-jest.spec.ts @@ -47,6 +47,7 @@ describe('setup-jest', () => { beforeEach(() => { delete globalThis.ngJest; + delete globalThis.TextEncoder; jest.clearAllMocks(); jest.resetModules(); }); @@ -78,6 +79,12 @@ describe('setup-jest', () => { errorOnUnknownProperties: true, }); }); + + test('should always have TextEncoder in globalThis', async () => { + await import('../../setup-jest'); + + expect(globalThis.TextEncoder).toBeDefined(); + }); }); describe('for ESM setup-jest, test environment initialization', () => { @@ -107,5 +114,11 @@ describe('setup-jest', () => { errorOnUnknownProperties: true, }); }); + + test('should always have TextEncoder in globalThis', async () => { + await import('../../setup-jest.mjs'); + + expect(globalThis.TextEncoder).toBeDefined(); + }); }); });