reactjs - 您如何使用 jest 和酶测试功能组件中的反应状态?
问题描述
我有一个名为的功能组件StoreLocator
,想测试它的状态是否会改变?
我知道是否StoreLocator
是一个class
组件,我可以使用以下方法测试它instance
:
describe('chooseMap', () => {
it('updates currentMap using location passed to it', () => {
const mountedStoreLocator = shallow(<StoreLocator />);
const mockEvent = 'testland.png';
mountedStoreLocator.instance().chooseMap(mockEvent);
expect(mountedStoreLocator.instance().state.currentMap).toBe('testland.png');
})
})
但是当我尝试下面的代码在功能组件中实现同样的事情并挂钩时它不起作用:
describe('chooseMap', () => {
it('updates currentMap using location passed to it', () => {
const mountedStoreLocator = shallow(<StoreLocator />);
const mockEvent = 'testland.png';
mountedStoreLocator.chooseMap(mockEvent);
expect(mountedStoreLocator.currentMap).toBe('testland.png');
})
})
它说TypeError: mountedStoreLocator.chooseMap is not a function
这是StoreLocator
组件:
export default function StoreLocator({location}) {
const [currentMap, setCurrentMap] = useState('none.png');
const shops = [
{
location: "Portland",
address: "123 Portland Dr",
},
{
location: "Astoria",
address: "123 Astoria Dr",
},
{
location: "",
address: "",
},
];
const chooseMap = (location) => {
setCurrentMap(location);
}
return (
<div>
<Header />
<div>
{shops.map((shop, index) => (
<Button handleClick={chooseMap} location={shop.location} key={index} />
))}
</div>
<Map imageName={currentMap} location={location} />
</div>
);
}
EDIT
正如评论中提到的@RafaelTavares,我已经进行了如下测试:
describe('change image correctly', () => {
it('should call handleClick on button click', () => {
const mountedStoreLocator = shallow(<StoreLocator />);
const map = mountedStoreLocator.find('Map');
expect(map.prop('imageName')).toBe('none.png');
const astoriaBtn = mountedStoreLocator.find('Button[location="Astoria"]');
astoriaBtn.invoke('handleClick')('Astoria');
expect(map.prop('imageName')).toBe('Astoria');
expect(astoriaBtn.length).toBe(1);
})
})
但仍然没有运气,我的测试将因这条消息而失败:
Expected: "Astoria"
Received: "none.png"
解决方案
推荐阅读
- angularjs - 如何使用量角器导航到网站中的页面而不是主页并在其中进行测试操作?
- raspberry-pi - 将任何 USB 密钥插头安装在同一文件夹中的 USB 端口上
- pyspark - 解析 pyarrow.parquet.ParquetDataset 对象的模式
- javascript - 在一个函数中执行多个函数
- excel - 修剪和字典不能一起工作
- c# - 当我点击 dataGridView 时,它说索引超出范围必须是非负数并且小于集合的大小
- angular - 指定要在 Angular 中使用的 NPM 模块平台
- ios - 将 12 位刻度转换为日期
- angular - Angular 4 高图表
- intellij-plugin - 如何将文件添加到 PbxGroupPsiElement - AppCode 插件开发