diegomura / react-pdf

📄 Create PDF files using React
https://react-pdf.org
MIT License
14.66k stars 1.17k forks source link

TextEncoder is not defined #2054

Open njoel24 opened 1 year ago

njoel24 commented 1 year ago

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

ghost commented 1 year ago

With react-pdf/renderer 3.0.0 you can get rid of jsdom environment and use default node without issues.

ghost commented 1 year ago

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.

vpfaulkner commented 1 year ago

Just upgraded to 3.0.0 and also am running into this issue. Will take a closer look on Monday.

Akshaykoushik06 commented 1 year ago

@vpfaulkner, I am running into the same issue. I tried the approach suggested by @njoel24, but no luck. Any update on this bug?

leq382121 commented 1 year ago

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.

leq382121 commented 1 year ago

@vpfaulkner @Akshaykoushik06 have you come up with any solution?

vpfaulkner commented 1 year ago

@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
kevin-dev71 commented 3 months ago

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,
}