I have a working react app, where I use msw
for mocking BE in browser and in tests (Jest).
With msw v1.3.0 everything works perfectly fine, I've decided to update it v2.0 and there I've encountered problems. All my tests fail because of the error ReferenceError: TextEncoder is not defined
. In browser mode it works fine though.
I've contacted msw
support and they told me this issue is Jest related. I've tried many workarounds how to define TextEncoder
in usual cases where that might work, but all in vain.
p.s. all versions are new (node: v18.14.2, npm: v9.5.0, typescript: v4.9.5, react: v18.2.0, jest: v27.5.1). And I run my tests with craco test
I've tried to create a separate jest.config.js
file and define TextEncoder
like this:
module.exports = {
globals: {
TextEncoder: require('util').TextEncoder,
TextDecoder: require('util').TextDecoder,
}
}
and from the file:
module.exports = {
setupFiles: ['<rootDir>/setupFiles.js'],
}
I've tried to import TextEncoder from 'util' and 'node:util':
const { TextDecoder, TextEncoder } = require('node:util');
Object.defineProperties(globalThis, {
TextDecoder: { value: TextDecoder, writable: true },
TextEncoder: { value: TextEncoder, writable: true },
});
I've tried to import it from the different external 'text-encoding' libraries.
And add testEnvironment: 'node'
in configs.
But all of that doesn't work for my case.
craco test
command. I should have added those configs into craco config in jest section instead of putting it into jest configs, which was not working. – Reparable