How to check HTML of processed React component?

The My React component has a suggestionRenderer property that allows you to specify how the component is rendered. For instance:

 <Autosuggest suggestions={getSuburbs} suggestionRenderer={renderLocation} /> 
 function renderLocation(suggestion, input) { return ( <span><strong>{suggestion.slice(0, input.length)}</strong>{suggestion.slice(input.length)}</span> ); } 

Now I would like to write a joke test to make sure that suggestionRenderer is doing its job. Checking myElement.getDOMNode().innerHTML shows:

 <span data-reactid=".9.1.$suggestion0.0"><strong data-reactid=".9.1.$suggestion0.0.0">M</strong><span data-reactid=".9.1.$suggestion0.0.1">ill Park</span></span> 

which is not particularly useful.

Is there a way to get pure HTML without React attributes?

+6
source share
2 answers

You can use React.renderToStaticMarkup for this.

 expect(React.renderToStaticMarkup( <Autosuggest ... suggestionRenderer{renderLocation}/> )) .to.be('<div>...') 

Or just take innerHTML and split it manually, but I don't know how reliable the cross browser will be:

 var reactAttrs = / data-react[-\w]+="[^"]+"/g myElement.getDOMNode().innerHTML.replace(reactAttrs, '') 

I used React.renderComponentToString and manually allocated data-react- attrs before adding React.renderToStaticMarkup .

+6
source

I don’t have unit test HTML at all (I believe that if unit tests of React are tested, the generated HTML is good, plus I intend to conduct an integration test with selenium to test HTML anyway), but I check that the component generates the correct virtual DOM.

I have a similar component, and the way I test autofill items is as follows.

 var testAutoCompleteItems = [{ display: 'test 1', value: 1 }, { display: 'test 2', value: 2 }, { display: 'test 3', value: 3 }]; //... it('should set items based on pass getData property', function(done) { Fiber(function() { testGlobals.component = React.render(<ExtendText onChange={testHelper.noop} getData={getData} />, div); var input = TestUtils.findRenderedDOMComponentWithClass(testGlobals.component, 'extend-text__display-input'); TestUtils.Simulate.focus(input); testHelper.sleep(5); var autoCompleteContainer = TestUtils.findRenderedDOMComponentWithClass(testGlobals.component, 'extend-text__auto-complete-container'); var autoCompleteItems = TestUtils.scryRenderedDOMComponentsWithTag(autoCompleteContainer, 'li'); //make sure elements are correct autoCompleteItems.forEach(function(item, key) { expect(item.props['data-key']).to.equal(key); expect(item.props.children).to.equal(testAutoCompleteItems[key].display); }); //make sure there is the correct number of elements expect(autoCompleteItems.length).to.equal(3); done(); }).run(); }); 
+2
source

Source: https://habr.com/ru/post/983628/


All Articles