You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Enzyme进行Shallow Rendering时实际与预期输出不匹配求助

Troubleshooting Your Counter.displayValue() Test Failure

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:

  1. 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");
    });
    
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 08:14:08