typescript Jest:Class extends value #< Object>不是构造函数或null

w6mmgewl  于 2023-05-01  发布在  TypeScript
关注(0)|答案(1)|浏览(212)

我开了个玩笑。env.js文件-我将其添加到jest中。config.js testEnvironment: './jest.env.js'-处理TextEncoderTextDecoder。但是在我的配置中,我在测试中确实得到了这个错误(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') {

我想了解错误本身,当然我想知道如何修复它
我的测试会成功的,如果我加上

global.TextEncoder = require('util').TextEncoder
global.TextDecoder = require('util').TextDecoder

而不是使用testEnvironment

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
    }
  }
}
6rqinv9w

6rqinv9w1#

你必须像这样导入TestEnvironment
const NodeEnvironment = require("jest-environment-node").TestEnvironment;
Mentionned here in the doc

相关问题