【问题标题】:React Test: Invariant Violation: Element type is invalid: undefined反应测试:不变违规:元素类型无效:未定义
【发布时间】:2016-08-31 10:52:36
【问题描述】:

你好,我正在学习 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.

【问题讨论】:

    标签: reactjs mocha.js redux jsdom


    【解决方案1】:

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

    export default AddTodo
    

    但将其导入为命名导出

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

    所以 AddTodo 是未定义的。

    将您的导入更改为:

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

    【讨论】:

      猜你喜欢
      • 2016-07-20
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      • 2019-12-31
      • 2019-05-09
      • 2019-04-17
      • 2020-07-02
      • 2021-02-25
      相关资源
      最近更新 更多