7

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

<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'd like to write a jest test to make sure that suggestionRenderer does its job. Inspecting myElement.getDOMNode().innerHTML reveals:

<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 a clean HTML, without React attributes?

4

2 回答 2

6

你可以用React.renderToStaticMarkup这个。

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

或者只是手动抓取innerHTML并剥离它,但我不知道跨浏览器的可靠性如何:

var reactAttrs = / data-react[-\w]+="[^"]+"/g

myElement.getDOMNode().innerHTML.replace(reactAttrs, '')

在添加之前,我曾经使用React.renderComponentToString并手动删除attrs 。data-react-React.renderToStaticMarkup

于 2015-03-11T06:09:26.263 回答
2

我通常不对 HTML 进行单元测试(我认为如果 React 的单元测试通过,那么生成的 HTML 很好,而且我打算与 selenium 进行集成测试以测试 HTML)但我确实测试了组件正在生成正确的虚拟 DOM。

我有一个类似的组件,我测试自动完成项目的方式看起来像这样。

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();
});
于 2015-03-11T08:23:23.213 回答