2015-06-12 30 views
11

Voglio testare un componente React con Shallow Rendering. Ma voglio testare il componente a seconda del suo stato.Imposta stato con React Shallow Rendering

Qual è il modo corretto di farlo? Ho provato questo:

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

    renderResult = shallowRenderer.getRenderOutput(); 

Ma non riesco a farlo funzionare. Qual è il modo corretto di impostare lo stato quando si esegue il rendering superficiale?

+0

Che cosa significa l'aspetto componente TweetsBox come? Di solito avresti uno stato iniziale. Quindi potrebbe essere attivato un tipo di evento per modificare lo stato. –

risposta

2

Non sembra come lo shallowRenderer restituito dal React.addons.TestUtils.createRenderer ha la capacità di fare molto a parte rendering sulla base dei componenti, oggetti di scena, e bambini passati in.

ho dovuto usare jsdom + React.addons.TestUtils.renderIntoDocument per impostare lo stato tramite un evento (come ha commentato @ neil-kistner). Immagino sia lo stesso se vuoi chiamare direttamente lo setState.

Ecco cosa ha funzionato per 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);  
    }); 
}); 
Problemi correlati