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

React Test: Invariant Violation: Element type is invalid: undefined

你好我在学习React/redux

我创建了一个待办事项应用程序,它工作正常,但是当我尝试用 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.

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

export default AddTodo

但将其导入为名为 export

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

所以 AddTodo 是未定义的。

将您的导入更改为:

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