1

I'm trying to test react application with Jest and Enzyme (React v18, Jest v29.4.3, and Enzyme-adapter 16). The tests are simple as shown on the example below: jest.test.file:

import React from 'react';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import { shallow } from 'enzyme';
import App from './App';
import Notifications from '../Notifications/Notifications';
import { StyleSheetTestUtils } from 'aphrodite';

Enzyme.configure({ adapter: new Adapter() });

let wrapper;
    
beforeEach(() => {
  wrapper = shallow(<App />);
  StyleSheetTestUtils.suppressStyleInjection();
});

afterEach(() => {
  StyleSheetTestUtils.clearBufferAndResumeStyleInjection();
});

describe('testing <App /> component', () => {

  it("<App /> is rendered without crashing", () => {
    expect(wrapper.render()).not.toBeNull();
  });

  it("<App /> contains the <Notifications /> Component", () => {
    expect(wrapper.contains(<Notifications />)).not.toBe(null);
  });
})

The problem is whenever I'm trying to run the test it fails, and I have a ReferenceError error:

FAIL  src/App/App.test.js
  ● Test suite failed to run

    ReferenceError: TextEncoder is not defined

      1 | import React from 'react';
      2 | import Enzyme from 'enzyme';
    > 3 | import Adapter from 'enzyme-adapter-react-16';
        | ^
      4 | import { mount, shallow } from 'enzyme';
      5 | import App from './App';
      6 | import Notifications from '../Notifications/Notifications';

      at node_modules/react-dom/cjs/react-dom-server.browser.development.js:145:19
      at Object.<anonymous> (node_modules/react-dom/cjs/react-dom-server.browser.development.js:7002:5)
      at Object.<anonymous> (node_modules/react-dom/server.browser.js:9:7)
      at Object.<anonymous> (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:5:1)
      at Object.require (node_modules/enzyme-adapter-react-16/src/index.js:2:18)
      at Object.require (src/App/App.test.js:3:1)
...

The solution I tried already:

  • add global.TextEncoder = TextEncoder; global.TextDecoder = TextDecoder; on the top of the test file.
  • add a config file in node_modules/whatwf-url/lib where I implement the following script:
'use strict';
const {TextDecoder, TextEncoder} = require('util')
const utf8Encoder = new TextEncoder();
const utf8Decoder = new TextDecoder("utf-8", { ignoreBOM: true });
function utf8Encoder(string) {
  return utf8Encoder.encode(string);
};

function utf8DecoderWithoutDom(bytes) {
  return utf8Decoder.decode(bytes);
};

module.exports = {
  utf8Encoder,
  utf8DecoderWithoutDom
}

I browsed many solutions beyond the above ones but still no way to fix the error.

Moez Ben Rebah
  • 170
  • 1
  • 12

0 Answers0