如何用Jest测试React组件的<h3>标题?测试失败原因解析
Element
Problem
I have a simple React component with two buttons and a title field. I've already tested the button click functionality, but now I need to test the title text inside the <h3> tag. Here's my component code:
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 code looks like this:
test('Text test ', ()=>{ const component = shallow( <Popup config={config}/> ); expect(component.find('h3')).toEqual("h3"); });
The test fails with this error:
Error: expect(received).toEqual(expected) // deep equality
Expected: "h3"
Received: {}
Can someone explain what's wrong here?
Solution
The issue here is how you're interacting with the Enzyme wrapper returned by shallow().find('h3'):
What's actually happening: When you call
component.find('h3'), it doesn't return a string like "h3" — instead, it returns an Enzyme Wrapper object (or a collection of wrappers) that represents the matched DOM element(s). Comparing this object directly to the string "h3" will always fail, which is why you're seeing theReceived: {}error (the object is being serialized as an empty object in the error message).How to fix it:
- First, make sure your
configvariable has a definedtextvalue for testing (you probably already have this, but it's worth making explicit):const config = { text: "My Test Title", back: jest.fn(), next: jest.fn() }; - To test the text inside the
<h3>tag, use the.text()method on the wrapper to extract its content, then compare that to your expected string:test('Text test ', ()=>{ const config = { text: "My Test Title", back: jest.fn(), next: jest.fn() }; const component = shallow(<Popup config={config}/>); expect(component.find('h3').text()).toEqual("My Test Title"); }); - If you just want to verify that the
<h3>element exists (rather than checking its text), use the.exists()method instead:expect(component.find('h3').exists()).toBe(true);
- First, make sure your
The key takeaway is that Enzyme's find() method returns wrapper objects that have their own set of methods for querying and asserting against the DOM elements they represent — you can't directly compare them to raw strings.
内容的提问来源于stack exchange,提问作者D.Anush

