我有一个简单的组件,其中包括两个按钮和标题字段。到目前为止,我已经测试了按钮的单击,但是我想测试<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(receive).toEqual(expected)//深度相等 预期:“ h3” 收到:{}
出了什么问题? 请解释吗?
谢谢。
答案 0 :(得分:1)
.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