jest
jest copied to clipboard
TypeError: 'removeEventListener' called on an object that is not a valid instance of EventTarget.
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?
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();
});
});
});
Possibly related: https://github.com/jsdom/jsdom/issues/2156
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.