无法读取未定义的反应测试库的 属性 'addListener'

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

我正在尝试使用 react 测试库 测试我的 antd 应用程序,但我不断收到此错误:

TypeError: Cannot read property 'addListener' of undefined

我正在使用自定义渲染,但错误似乎来自 'render' 方法。

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

我什至使用相同版本的 react 和 react-dom(这似乎是 rtl 的常见问题)。

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

有问题的组件似乎是这样的:

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>
    );
}

antd 的 List 组件中的 'antd/lib/_util/responsiveObserve' 模块似乎出错了。取出该组件使测试工作(虽然显然我不想从我的应用程序中删除它)。

问题是在测试期间 document 不存在。您可以使用像 jsdom 这样的库: https://github.com/jsdom/jsdom

您是否在您的笑话 setupTest.js 文件中使用定义 window.matchMedia?对我来说修复它的是将它从 window.matchMedia 移动到 global.matchMedia 就像他们在 this repo.

中所做的那样

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

试试下面的代码,它对我有用。

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