Upon setting up a jest.env.js file and adding it to jest.config.js testEnvironment: './jest.env.js'
, I encountered an error related to TextEncoder
and TextDecoder
while running tests with jest@28:
TypeError: Class extends value #<Object> is not a constructor or null
> 7 | module.exports = class CustomTestEnvironment extends NodeEnvironment {
| ^
8 | async setup() {
9 | await super.setup()
10 | if (typeof this.global.TextEncoder === 'undefined') {
I am looking to understand the root cause of the error and how to resolve it
To make my tests work without errors, I found that I needed to add the following lines at the beginning of my testfile instead of using testEnvironment
:
global.TextEncoder = require('util').TextEncoder
global.TextDecoder = require('util').TextDecoder
Modified jest.env.js
const NodeEnvironment = require('jest-environment-node')
module.exports = class CustomTestEnvironment extends NodeEnvironment {
async setup() {
await super.setup()
if (typeof this.global.TextEncoder === 'undefined') {
const { TextEncoder } = require('util')
this.global.TextEncoder = TextEncoder
}
if (typeof this.global.TextDecoder === 'undefined') {
const { TextDecoder } = require('util')
this.global.TextDecoder = TextDecoder
}
}
}