使用Enzyme进行Shallow Rendering时实际与预期输出不匹配求助
Let's break down why your test is failing and how to fix it:
The Root Cause
Your test fails because Enzyme's contains method uses strict object equality (Object.is) when comparing JSX elements. The <div>188</div> you pass to contains is a brand-new JSX object, separate from the one returned by c1.displayValue(). Even though they look identical, they're not the same object in memory—so the check returns false.
Quick Fixes for Your Current Code
You don't need to rewrite your Counter class to get the test passing. Here are two reliable alternatives:
Check the text content directly (the simplest and most readable approach):
it("renders a div with the correct value", () => { const wrapper = shallow(c1.displayValue()); expect(wrapper.text()).toBe("188"); });Use a matcher object with
contains(if you want to verify the element structure explicitly):it("renders a div with the correct value", () => { const wrapper = shallow(c1.displayValue()); expect(wrapper.contains({ type: "div", props: { children: "188" } })).toBe(true); });
Bonus: Refactor to Follow React Best Practices
While your current code works, your Counter isn't a standard React component (it doesn't inherit from React.Component). If you plan to use this as a React component long-term, here's how to refactor it properly:
import React from 'react'; export default class Counter extends React.Component { // Use React state for reactive values (instead of class properties) state = { counterValue: 0 }; update(newValue) { this.setState({ counterValue: newValue }); } getValue() { return this.state.counterValue; } // React components use a dedicated render method instead of custom display methods render() { return <div>{this.getValue()}</div>; } }
And the corresponding test would follow standard React component testing patterns:
describe("check Counter component", () => { it("renders the updated value", () => { const wrapper = shallow(<Counter />); const counterInstance = wrapper.instance(); counterInstance.update(188); wrapper.update(); // Force re-render after state change expect(wrapper.text()).toBe("188"); }); });
内容的提问来源于stack exchange,提问作者jin cheng teo

