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?
- 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
3 Answers
Reset to default 4At 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)