本文介绍了无法读取未定义的 react-testing-library 的属性“addListener"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

TypeError: 无法读取未定义的属性addListener"

我正在使用自定义渲染,但错误似乎来自渲染"方法.

const customRender = (ui, options) =>渲染(用户界面,{包装:TestingWrapper,...选项})^

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

反应":17.0.1",react-dom":17.0.1",

问题组件似乎是这样的:

import React, {懒惰的,悬念来自'反应';从 'antd/lib/list' 导入列表;const 故事 = (道具) =>{返回(<div className="stories-container"><div><h1 className="StoriesTitle">Stories</h1>

<div className=StoryListContainer"><Suspense fallback={<Spin/>}><列表itemLayout=垂直"大小=默认";分页={分页}数据源={故事}renderItem={item =><故事项目项目={项目}deleteFn={onDelete}登录={登录}故事={故事}/>}/></悬念>

);}

它似乎在模块 'antd/lib/_util/responsiveObserve' 中出错,该模块是 antd 的 List 组件的一部分.去掉那个组件可以让测试工作(虽然显然我不想从我的应用程序中删除它).

解决方案

您可能在 jest setupTest.js 文件中使用定义 window.matchMedia 吗?对我来说修复它的是将它从 window.matchMedia 移动到 global.matchMedia 就像他们在 这个仓库.

global.matchMedia = global.matchMedia ||功能 () {返回 {addListener: jest.fn(),removeListener: jest.fn(),};};

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

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

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

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).

解决方案

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

这篇关于无法读取未定义的 react-testing-library 的属性“addListener"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 02:43