最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - FileReader, File and TextDecoder in Jest Test not defined - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question edited Apr 5, 2019 at 7:54 skyboyer 23.8k7 gold badges62 silver badges71 bronze badges asked Apr 4, 2019 at 17:26 SebastianSebastian 9722 gold badges15 silver badges42 bronze badges 1
  • Importing them into your tests? Or use setupFiles to import all the modules required globally for all test suites. – josephting Commented Apr 5, 2019 at 0:55
Add a ment  | 

3 Answers 3

Reset to default 4

At least for TextDecoder I've found a way around with the help of @josephting's ment. 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,
  }
}

If you're using Jest then the best solution is from Arthur Medeiros: Just allow jest to have access to the appropriate global variables it needs. Note that you probably don't need to import util since TextDecoder and TextEncoder should be on the global scope in your jest config file; you only need globals: { TextDecoder, TextEncoder }, in your config file's export.

But there could be times where you're don't want to include these globals for all tests in your suite (and don't want to have another config file), or are using something other than jest. In those cases you can just add this to your test file:

import { TextDecoder, TextEncoder } from 'node:util'; // (ESM style imports)

global.TextDecoder = TextDecoder;
global.TextEncoder = TextEncoder;

// Do whatever you wanted to do... (for me, it was using node-fetch)
发布评论

评论列表(0)

  1. 暂无评论