反应测试:不变违规:元素类型无效:未定义

时间:2016-05-05 15:13:35

标签: reactjs mocha redux jsdom

您好我正在学习React / redux

我创建了一个todo应用程序,它工作正常,但是当我尝试用jsdom编写组件测试时,它向我显示了这个错误,花了一些时间但是无法弄清楚问题:

组件(它只是一个文本字段+按钮)

import React from 'react'
import {addTodo} from '../actions'
import {connect} from 'react-redux'

let inputText

class AddTodo extends React.Component {
    constructor(props, context){
        super(props, context)
    }

    render(){
        const {text, handleAdd} = this.props
        return (
            <div>
                Text:  
                <input type='text' ref={node=>{ inputText=node}} /> <button onClick={()=>handleAdd(inputText.value)} >Add </button>
            </div>
        )
    }
}

 const handleAdd = (text)=>{
           dispatch(addTodo(text))
        }

const mapDispatchToProps = (dispatch, ownProps) =>{
    return {
        handleAdd: (text)=>{
           dispatch(addTodo(text))
        }
    }
}

AddTodo = connect(null,mapDispatchToProps)(AddTodo)

export default AddTodo

spec.js

import React from 'react'
import ReactDOM from 'react-dom'
import {
    renderIntoDocument,
    scryRenderDOMComponentsWithTag,
    Simulate
} from 'react-addons-test-utils'
import {AddTodo} from '../../src/containers/AddTodo'
import {expect} from 'chai'

describe('Add todo', ()=>{
    it('render the button and text field', ()=>{
        const component = renderIntoDocument(<AddTodo />);
        const button = scryRenderDOMComponentsWithTag(component, 'button');
        const input = scryRenderDOMComponentsWithTag(component, 'input');
        expect(button.length).to.be(1);
        expect(input.length).to.be(1);
    }) 
})

错误:

Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

1 个答案:

答案 0 :(得分:2)

您将组件导出为默认导出:

export default AddTodo

但是将其导入为命名导出

import {AddTodo} from '../../src/containers/AddTodo'

所以AddTodo未定义。

将导入更改为:

import AddTodo from '../../src/containers/AddTodo'