I have a simple component which includes two buttons and the heading field. So far I tested button clicks but I want to test heading text field in the <h3>
tag.
My component
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>
);
}
}
My test
test('Text test ', ()=>{
const component = shallow(
<Popup config={config}/>
);
expect(component.find('h3')).toEqual("h3");
});
My test fails with
Error: expect(received).toEqual(expected) // deep equality Expected: "h3" Received: {}
What went wrong? Explanation pls?
Thanks.
.find(selector) => ShallowWrapper returns shallow wrapper, obviously, the shallow wrapper is not equal to the string h3
. If you want to get the text of this h3
shallow wrapper, you need to call .text() => String on the shallow wrapper.
E.g.
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');
});
});
unit test results:
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