Skip to content

Commit c0af6c3

Browse files
committed
feat: add polyfill for TextEncoder
fixes #1914 fixes #2514
1 parent 09847bc commit c0af6c3

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

setup-jest.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,18 @@
11
require('zone.js');
22
require('zone.js/testing');
3+
const { TextEncoder, TextDecoder } = require('util');
4+
35
const { getTestBed } = require('@angular/core/testing');
46
const {
57
BrowserDynamicTestingModule,
68
platformBrowserDynamicTesting,
79
} = require('@angular/platform-browser-dynamic/testing');
810

11+
if (typeof globalThis.TextEncoder === 'undefined') {
12+
globalThis.TextEncoder = TextEncoder;
13+
globalThis.TextDecoder = TextDecoder;
14+
}
15+
916
const testEnvironmentOptions = globalThis.ngJest?.testEnvironmentOptions ?? Object.create(null);
1017

1118
getTestBed().initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting(), testEnvironmentOptions);

setup-jest.mjs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,12 @@ import 'zone.js';
22
import 'zone.js/testing';
33
import { getTestBed } from '@angular/core/testing';
44
import { BrowserDynamicTestingModule, platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
5+
import { TextEncoder, TextDecoder } from 'util';
6+
7+
if (typeof globalThis.TextEncoder === 'undefined') {
8+
globalThis.TextEncoder = TextEncoder;
9+
globalThis.TextDecoder = TextDecoder;
10+
}
511

612
const testEnvironmentOptions = globalThis.ngJest?.testEnvironmentOptions ?? Object.create(null);
713

src/config/setup-jest.spec.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ describe('setup-jest', () => {
4747

4848
beforeEach(() => {
4949
delete globalThis.ngJest;
50+
delete globalThis.TextEncoder;
5051
jest.clearAllMocks();
5152
jest.resetModules();
5253
});
@@ -78,6 +79,12 @@ describe('setup-jest', () => {
7879
errorOnUnknownProperties: true,
7980
});
8081
});
82+
83+
test('should always have TextEncoder in globalThis', async () => {
84+
await import('../../setup-jest');
85+
86+
expect(globalThis.TextEncoder).toBeDefined();
87+
});
8188
});
8289

8390
describe('for ESM setup-jest, test environment initialization', () => {
@@ -107,5 +114,11 @@ describe('setup-jest', () => {
107114
errorOnUnknownProperties: true,
108115
});
109116
});
117+
118+
test('should always have TextEncoder in globalThis', async () => {
119+
await import('../../setup-jest.mjs');
120+
121+
expect(globalThis.TextEncoder).toBeDefined();
122+
});
110123
});
111124
});

0 commit comments

Comments
 (0)