簡體   English   中英

React.js測試無法找到組件

[英]React.js test fails on finding components

我有一個基於React,Redux和React-router的應用程序構建。 我正在使用React TestUtils編寫測試,發現從測試中您可以看到以下內容。 第一個expect(nav).to.have.length(1);作品: expect(nav).to.have.length(1); 但是第二個expect(modal).to.have.length(1);

失敗:

AssertionError:預期[]的長度為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 }; 

APP-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元素。

搜尋需要組件參考iirc。 所以:

import Modal from './components/modal';

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

這將查找實際組件的實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM