我在React,Redux和React-router上构建了一个app。我正在使用React TestUtils编写测试,我发现从下面的测试中可以看到。
第一个期望是有效的:expect(nav).to.have.length(1);
但第二个expect(modal).to.have.length(1);
失败了:
AssertionError:expect []的长度为1,但得到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
};
&#13;
应用-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);
});
});
&#13;
答案 0 :(得分:0)
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元素。
答案 1 :(得分:0)
scrying需要一个组件参考iirc。所以:
import Modal from './components/modal';
// Then later:
const modal = scryRenderedComponentsWithType(component, Modal);
这将查找实际组件的实例。