Cannot read property 'addListener' of undefined react-testing-library

北城以北 提交于 2021-01-23 05:42:09

问题


I'm trying to test my antd application with react testing library, but I keep getting this error:

TypeError: Cannot read property 'addListener' of undefined

Im using a custom render but the error seems to be coming from the 'render' method.

const customRender = (ui, options) => render(ui, { wrapper: TestingWrapper, ...options }) ^

I´m even using the same versions of react and react-dom (which seems to be a common issue with rtl).

"react": "17.0.1", "react-dom": "17.0.1",

The problematic component seems to be this:

import React, {
  lazy,
  Suspense
} from 'react';

import List from 'antd/lib/list';
  
const Stories = (props) => {
    return(
  <div className="stories-container">

    <div>
      <h1 className="StoriesTitle">Stories</h1>
    </div>

    <div className="StoryListContainer">
     <Suspense fallback={<Spin />}>
        <List
          itemLayout="vertical"
          size="default"
          pagination={pagination}
          dataSource={stories}
          renderItem={item =>
            <StoryItem
              item={item}
              deleteFn={onDelete}
              loggedIn={loggedIn}
              stories={stories}
            />
          }
        />
      </Suspense>
    </div>

  </div>
    );
}

It seems to error out in the module 'antd/lib/_util/responsiveObserve' which is a part of antd's List component. Taking that component out makes the test work (though obviously I don't want to remove it from my application).


回答1:


Are you perhaps using defining window.matchMedia in your jest setupTest.js file? What fixed it for me is to move it from window.matchMedia to global.matchMedia like how they did it in this repo.

global.matchMedia = global.matchMedia || function () {
  return {
    addListener: jest.fn(),
    removeListener: jest.fn(),
  };
};



回答2:


The problem is that during the tests document does not exist. You can use a library like jsdom: https://github.com/jsdom/jsdom




回答3:


Try the below code, which works for me.

  delete window.matchMedia
  window.matchMedia = (query) => ({
    matches: false,
    media: query,
    onchange: null,
    addListener: jest.fn(), // deprecated
    removeListener: jest.fn(), // deprecated
    addEventListener: jest.fn(),
    removeEventListener: jest.fn(),
    dispatchEvent: jest.fn(),
  })


来源:https://stackoverflow.com/questions/64813447/cannot-read-property-addlistener-of-undefined-react-testing-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!