React.js 查找组件时测试失败

React.js test fails on finding components

我有一个基于 React、Redux 和 React-router 构建的应用程序。我正在使用 React TestUtils 编写测试,我发现从下面的测试中可以看出这一点。 第一个期望有效:expect(nav).to.have.length(1); 但是第二个 expect(modal).to.have.length(1);

失败:

AssertionError: expected [] to have a length of 1 but got 0

App.js:

import React, { Component, cloneElement, PropTypes } from 'react';
import ContactsList from './contactsList';
import Nav from './nav';
import Modal from './modal';
import Header from './header';
import HomeIndex from './homeIndex';
import ErrorBox from './errorBox';
import ImmutablePropTypes from 'react-immutable-proptypes';

export default class App extends Component {
 render = () => {
  const { actions, contacts, router } = this.props;
  return (
   <div>
    <Nav />
    <div className="container">
     <ErrorBox error={contacts.getIn(['error', 'errorMessage'])} show={contacts.getIn(['error', 'showError'])} />
     <Header />
     <div className="contacts-list-container">
      <ContactsList contacts={contacts} />
      <Modal open={contacts.get('showSpinner')} />
      { cloneElement(this.props.children || <HomeIndex/>, { contacts: contacts ,
        addContact: actions.addContactReq, 
        getContact: actions.getContact, 
        contact: contacts.get('contact'), 
        router: router,
        deleteContact: actions.deleteContact,
        editContact: actions.editContact }) }
     </div>
    </div>    
   </div>
  );
 }
}

App.propTypes = {
 actions: PropTypes.object.isRequired,
 contacts: ImmutablePropTypes.map.isRequired,
 router: PropTypes.object.isRequired
};

应用-spec.js:

import React from 'react';
import { renderIntoDocument, scryRenderedDOMComponentsWithTag } from 'react-addons-test-utils';
import { expect } from 'chai';
import App from '../components/app';
import { Map } from 'immutable';

describe('app', () => {

 it('renders properly', () => {
  const component = renderIntoDocument(
   <App  actions={{}} router={{}} contacts={ Map({
    showSpinner: false,
    error: Map({
     showError: false,
     errorMessage: ''
    }),
    contacts: Map(),
    contact: Map()
    }) } />
  );

  const nav = scryRenderedDOMComponentsWithTag(component, 'Nav');
  const modal = scryRenderedDOMComponentsWithTag(component, 'Modal');
  expect(nav).to.have.length(1);
  expect(modal).to.have.length(1);      
 });
});

scryRenderedDOMComponentsWithTag 在组件 DOM 中查找实际的 HTML 元素。您想使用 scryRenderedComponentsWithType 来查找呈现的 React 组件:

const modal = scryRenderedComponentsWithType(component, Modal);

https://facebook.github.io/react/docs/test-utils.html#scryrenderedcomponentswithtype

您的 Nav 调用可能有效,因为您的 Nav React 组件中有一个 <nav> HTML 元素。

scrying 需要组件参考 iirc。所以:

import Modal from './components/modal';

// Then later:
const modal = scryRenderedComponentsWithType(component, Modal);

这将查找实际组件的实例。