无法读取未定义的react-testing-library的属性'addListener' [英] Cannot read property 'addListener' of undefined react-testing-library
问题描述
我正在尝试使用反应测试库对我的 antd 应用程序进行测试,但是我一直收到此错误:
I'm trying to test my antd application with react testing library, but I keep getting this error:
TypeError:无法读取未定义的属性'addListener'
TypeError: Cannot read property 'addListener' of undefined
我正在使用自定义渲染,但错误似乎出自'render'方法.
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})^
const customRender = (ui, options) => render(ui, { wrapper: TestingWrapper, ...options }) ^
我什至都在使用相同版本的react和react-dom(这似乎是rtl的常见问题).
I´m even using the same versions of react and react-dom (which seems to be a common issue with rtl).
反应":"17.0.1","react-dom":"17.0.1",
"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>
);
}
似乎在模块"antd/lib/_util/responseObserve"中出错了,该模块是antd的List组件的一部分.取出该组件即可进行测试(尽管显然我不想将其从应用程序中删除).
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).
推荐答案
您是否可能在Jest setupTest.js文件中使用定义window.matchMedia?对我来说,解决此问题的方法是将其从window.matchMedia移至global.matchMedia,就像他们在
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'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!