javascript - 用 enzyme 进行 react 测试TypeError : Cannot read property 'state' of undefined

标签 javascript reactjs enzyme jestjs

我正在尝试使用 浅层渲染 enzyme 对组件进行单元测试。尝试测试组件的状态 activeTab,它抛出 TypeError: Cannot read property state。我的组件 Accordion 。 Accordion 组件jsx代码

 class Accordion extends Component {
    constructor(props) {
        super(props)
        this.state = {
            activeTab: 0
        }
    }

    static defaultProps = {
        tabs: [{title: 'Status'}, {title: 'Movement'}]
    }

    render() {
        const { tabs } = this.props
            , { activeTab } = this.state
        return (
            <div className={`accordion`}>
                {tabs.map((t, i) => {
                    const activeClass = activeTab === i ? `accordion--tab__active` : ''
                    return(
                        <section key={i} className={`accordion--tab ${activeClass}`}>
                            <header className={`accordion--header`}>
                                <h4 className={`accordion--title`}>
                                    <button onClick={() => {this._selectAccordion(i)}}>{t.title}</button>
                                </h4>
                            </header>
                            <div className="accordion--content">
                                {t.title}
                                Content
                            </div>
                        </section>
                    )
                })}
            </div>
        )
    }
    _selectAccordion = activeTab => {this.setState({activeTab})}
}

export default Accordion

Accordion.react.test.js

import { shallow } from 'enzyme'
import Accordion from './components/Accordion'

test('Accordion component', () => {
    const component = shallow(<Accordion name={`Main`}/>)
    expect(component.state('activeTab')).equals(0)
})

最佳答案

这可能是一个范围界定问题。使用 React 中的事件处理程序,您必须将构造函数中的事件处理程序绑定(bind)到“this”。这是来自 React 的 docs 的一些信息关于它:

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

This is not React-specific behavior; it is a part of how functions work in JavaScript. Generally, if you refer to a method without () after it, such as onClick={this.handleClick}, you should bind that method.

class Accordion extends Component {
    constructor(props) {
        super(props)
        this.state = {
            activeTab: 0
        }

        // This binding is necessary to make `this` work in the callback
        this._selectAccordion = this._selectAccordion.bind(this);
    }

    static defaultProps = {
        tabs: [{title: 'Status'}, {title: 'Movement'}]
    }

        _selectAccordion(activeTab){
            this.setState({activeTab : activeTab})
        }

    render() {
        const { tabs } = this.props,
        { activeTab } = this.state
        return (
            <div className={`accordion`}>
                {tabs.map((t, i) => {
                    const activeClass = activeTab === i ? `accordion--tab__active` : ''
                    return(
                        <section key={i} className={`accordion--tab ${activeClass}`}>
                            <header className={`accordion--header`}>
                                <h4 className={`accordion--title`}>
                                    <button onClick={() => {this._selectAccordion(i)}}>{t.title}</button>
                                </h4>
                            </header>
                            <div className="accordion--content">
                                {t.title}
                                Content
                            </div>
                        </section>
                    )
                })}
            </div>
        )
    }

}

关于javascript - 用 enzyme 进行 react 测试TypeError : Cannot read property 'state' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46402943/

相关文章:

javascript - 替换 contenteditable div 的 html 后,如何将插入符号放在以前的位置?

reactjs - 编译失败 ./src/App.js Module not found : Can't resolve

javascript - 在 react 中使用自定义钩子(Hook)数组

reactjs - MUI 失败的 Prop 类型 : Invalid prop `color` of value `#ff9800` supplied to `ForwardRef(Link)` ,

reactjs - 使用 enzyme 测试 react 确认窗口

javascript - React onClick 和 onTouchStart 同时触发

javascript - WebRTC 如何设置限制以在可用时使用音频

javascript - Jest 遇到意外 token : SyntaxError: Unexpected Token {

javascript - 如何使用 Jest 和 Enzyme 为简单的 React 组件编写测试用例

javascript - jQuery .ajax() - 向 POST 请求添加查询参数?