react-pdf
react-pdf copied to clipboard
TextEncoder is not defined
Tech stack: Jest 27, react 17, react-pdf/renderer 3.0.0
When running a test that encounters the react-pdf/renderer, the file EncodeStream instantiates TextEncoder.
That class is not available in jsdom, thus jest throws an error.
Solution found for that was to mock usePDF directly or to inject node TextEncoder util in global variables like
in setupTests.js
import {TextEncoder} from 'util'
global.TextEncoder = TextEncoder
Would it be possible to avoid that and explicitly import TextEncoder from util within EncodeStream?
Thanks in advance
With react-pdf/renderer 3.0.0 you can get rid of jsdom
environment and use default node
without issues.
What's the issue having explicit define for test setup? We were using it before 3.0.0 and for jest-image-snapshots you need setup script anyway.
Just upgraded to 3.0.0 and also am running into this issue. Will take a closer look on Monday.
@vpfaulkner, I am running into the same issue. I tried the approach suggested by @njoel24, but no luck. Any update on this bug?
We use Create React App and Jest, I confirm that we also bump into this issue and this is really a pickle. Is ther any news? We juse jsdom but it's important for us to keep it.
@vpfaulkner @Akshaykoushik06 have you come up with any solution?
@leq382121 / @Akshaykoushik06 sorry, just seeing your questions...
It's been months since working on this code so don't fully remember the context but we have the following in our setup test code:
import { TextEncoder, TextDecoder } from 'util'
import '@testing-library/jest-dom'
// See https://github.com/diegomura/react-pdf/issues/2054#issue-1407270392
global.TextEncoder = TextEncoder
// @ts-ignore
global.TextDecoder = TextDecoder
my solution was to mock @react-pdf/renderer
// jest.config,mjs
moduleNameMapper: {
"@react-pdf/renderer": "<rootDir>/__mocks__/react-pdf/renderer.js",
},
// /__mocks__/react-pdf/renderer.js
const React = require("react")
const PDFDownloadLink = ({ children }) => <div>{children}</div>
const Document = ({ children }) => <div>{children}</div>
const Page = ({ children }) => <div>{children}</div>
const Text = ({ children }) => <span>{children}</span>
const View = ({ children }) => <div>{children}</div>
const StyleSheet = {
create: (styles) => styles,
}
const Font = {
register: () => {},
}
const PDFImage = ({ src, style }) => <img src={src} style={style} alt="" />
module.exports = {
PDFDownloadLink,
Document,
Page,
Text,
View,
StyleSheet,
Font,
Image: PDFImage,
}