reactjs - 如何使用 jest 测试反应组件的标题?
问题描述
我有一个简单的组件,其中包括两个按钮和标题字段。到目前为止,我测试了按钮点击,但我想测试<h3>
标签中的标题文本字段。
我的组件
class Popup extends React.Component {
render() {
return (
<div className="popupOuter">
<div className="popupInner text-center">
<br/>
<h3>{this.props.config.text}</h3>
<br/>
<div>
<Button type='NoButton' value={'No'} onClick={this.props.config.back} />
<Button type = 'YesButton' value={'Yes'} onClick={this.props.config.next}/>
</div>
</div>
</div>
);
}
}
我的测试
test('Text test ', ()=>{
const component = shallow(
<Popup config={config}/>
);
expect(component.find('h3')).toEqual("h3");
});
我的测试失败了
错误:expect(received).toEqual(expected) // 深度相等 Expected: "h3" Received: {}
什么地方出了错?请解释一下?
谢谢。
解决方案
.find(selector) => ShallowWrapper返回浅包装,显然,浅包装不等于字符串h3
。如果你想得到这个h3
浅包装的文本,你需要在浅包装上调用.text() => String。
例如
index.tsx
:
import React from 'react';
const Button = (props) => <button></button>;
export class Popup extends React.Component {
render() {
return (
<div className="popupOuter">
<div className="popupInner text-center">
<br />
<h3>{this.props.config.text}</h3>
<br />
<div>
<Button type="NoButton" value={'No'} onClick={this.props.config.back} />
<Button type="YesButton" value={'Yes'} onClick={this.props.config.next} />
</div>
</div>
</div>
);
}
}
index.test.tsx
:
import { Popup } from './';
import { shallow } from 'enzyme';
describe('60759790', () => {
it('should render text for h3', () => {
const mProps = { config: { text: 'h3' } };
const wrapper = shallow(<Popup {...mProps}></Popup>);
expect(wrapper.find('h3').text()).toEqual('h3');
});
});
单元测试结果:
PASS stackoverflow/60759790/index.test.jsx (8.126s)
60759790
✓ should render text for h3 (10ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.418s
推荐阅读
- python - 如何使用登录信息调用 MetaTrader5 `initialize()`?
- visual-studio-code - 更漂亮的不尊重 VSCode 设置文件
- datetime - 在 Google 表格中,如何将 [2021-10-08 23:49:37] 转换为 (-6) 时区,看起来像 [10-October-2021, 05:49:37 PM]
- javascript - 如何检查嵌套对象数组中是否存在特定单词
- angular - 如何使用 Angular 9 上传视频并将其存储在文件系统中?
- reactjs - 如何使用类组件传递参数并将其放入反应原生的另一个组件中
- html - 如何决定在哪里添加拖放事件监听器?
- django - 有没有办法让 EC2 实例中的请求保持超过 60 秒?
- r - 更改方法定义的源代码
- python - 仅包装类中方法的“最新”实现?