简体   繁体   中英

FileReader, File and TextDecoder in Jest Test not defined

before I only do tests with Jasmine now I try Jest but facing the problem that things like FileReader, File and TextDecoder are not defined in my tests. How can I use this classes with their real function to test my class that uses them?

At least for TextDecoder I've found a way around with the help of @josephting's comment. It's really hacky since it requires you to install a dev dependency that is also deprecated and no longer maintained called text-encoding .

First you need to define setupFiles in your jest.config.js :

[...]
setupFiles: ['./tests/setupEnv.js'],
[...]

And you also need to require the mentioned package globally in your setupEnv.js :

TextDecoder = require('text-encoding').TextDecoder;

I found a work around this issue, I added the TextEncoder and TextDecoder as a global variable in jest.

I added this to my jest.config

const { TextDecoder, TextEncoder } = require('util')

module.exports = {
  globals: {
    TextDecoder: TextDecoder,
    TextEncoder: TextEncoder,
  }
}

This worked for me, thanks! Arthur Medeiros

  const { TextDecoder, TextEncoder } = require('util')
    
    module.exports = {
      globals: {
        TextDecoder: TextDecoder,
        TextEncoder: TextEncoder,
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM