jest icon indicating copy to clipboard operation
jest copied to clipboard

TypeError: 'removeEventListener' called on an object that is not a valid instance of EventTarget.

Open p-iknow opened this issue 3 years ago • 2 comments

problem

When switching to swc/jest, the following error occurs when executing the test. It seems to be related to jsdom. I tried to figure out what the problem was, but I couldn't find a solution. Can I get help solving this problem?

image

TypeError: 'removeEventListener' called on an object that is not a valid instance of EventTarget.

  at JSDOMEnvironment.removeEventListener (node_modules/jsdom/lib/jsdom/living/generated/EventTarget.js:157:15)
  at tryCatch (node_modules/regenerator-runtime/runtime.js:49:25)
  at Generator.invoke [as _invoke] (node_modules/regenerator-runtime/runtime.js:175:30)
  at Generator.next (node_modules/regenerator-runtime/runtime.js:77:29)

jest-setting

The jest setting is as follows.

module.exports = {
  projects: ['<rootDir>/'],
  // swc/jest
  transform: {
    '^.+\\.(t|j)sx?$': ['@swc/jest', ],
  },
  //testEnvironment: "jsdom",
  testRegex: '\\.test\\.(ts|js)x?$',
  moduleNameMapper: {
    '@/(.*)$': '<rootDir>/src/$1',
    '@mocks/(.*)$': '<rootDir>/mocks/$1',
    '@pages/(.*)$': '<rootDir>/pages/$1'
  },
  setupFilesAfterEnv: [
    '<rootDir>/src/__test__/setup-tests.tsx',
  ],
  transformIgnorePatterns: [
    'node_modules/?!core-js',
  ],
  // https://jestjs.io/docs/jest-object#jestrestoreallmocks
  restoreMocks: true,
  clearMocks: true,
};

The test I executed

I'm using next.js and I'm doing the test below using react-testing-lib.

/**
 * @jest-environment jsdom
 */

import * as Factory from 'factory.ts';

import { render, screen } from '@/__test__/test-utils';
import {
  SummaryDetails,
  SummaryDetailType,
} from '@src/components/summary-details';

const summeryDetailFactory = Factory.Sync.makeFactory<SummaryDetailType>({
  title: Factory.each(i => i.toString()),
  value: Factory.each(i => `${i},000,000w`),
});
describe('<SummeryDetails/>', () => {
  it('render', () => {
    // Given
    const MOCK_SUMMARY_DETAILS = summeryDetailFactory.buildList(2);

    // When
    render(<SummaryDetails summaryDetails={MOCK_SUMMARY_DETAILS} />);

    // Then
    MOCK_SUMMARY_DETAILS.forEach(({ title, value }) => {
      expect(screen.getByText(title)).toBeInTheDocument();
      expect(screen.getByText(`${value}원`)).toBeInTheDocument();
    });
  });
});

p-iknow avatar Oct 27 '21 00:10 p-iknow

Possibly related: https://github.com/jsdom/jsdom/issues/2156

iChip avatar Oct 28 '21 22:10 iChip

In my case using default transformIgnorePatterns in jest config fixed the problem. Not sure how it's related, but maybe it will lead somone further. The error appeared with transformIgnorePatterns set to [], but when I removed this property from jest config, the tests with @swc/jest and @testing-library/react worked just fine.

librowski avatar Nov 22 '21 09:11 librowski