简体   繁体   中英

Set state with React Shallow Rendering

I want to test a React component with Shallow Rendering. But I want to test the component depending on its state.

What is the proper way of doing so? I have tried this:

  component = shallowRenderer.render(
    <TweetsBox
      users = 4
    />
  );
  component.setState({initial: true}); // This is not allowed

  renderResult = shallowRenderer.getRenderOutput();

But I can't make it work. What is the proper way of setting the state when doing shallow rendering?

It doesn't look like the shallowRenderer returned by React.addons.TestUtils.createRenderer has the ability to do much aside from render based on the component, props, and children passed in.

I had to use jsdom + React.addons.TestUtils.renderIntoDocument to set state via an event (as @neil-kistner commented). I imagine it's the same if you want to call setState directly.

Here's what worked for me:

import jsdom from "jsdom";
global.document = jsdom.jsdom("<!doctype html><html><body></body></html>");
global.window = document.parentWindow;
global.navigator = {
  userAgent: "node.js"
};
import React from "react/addons";
const TestUtils = React.addons.TestUtils;
import PriceAtTotalQuantity from "app/components/PriceAtTotalQuantity";
import { assert } from "chai";

describe("app/components/PriceAtTotalQuantity", function() {
  it("should show tooltip on mouseover", function() {
    const props = {
      currencyCode: "USD",
      offer: {
        priceWasConverted: true,
        priceAtTotalQuantity: 0.1
      }
    };
    var priceAtTotalQuantity = TestUtils.renderIntoDocument(React.createElement(PriceAtTotalQuantity, props));
    var currencyCodeNode = TestUtils.findRenderedDOMComponentWithClass(priceAtTotalQuantity, "currency-code").getDOMNode();
    assert.isFalse(priceAtTotalQuantity.state.tooltipIsVisible);
    TestUtils.Simulate.mouseOver(currencyCodeNode);
    assert.isTrue(priceAtTotalQuantity.state.tooltipIsVisible);    
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM