【问题标题】:unittest for reactjs component fails on function passed as propsreactjs 组件的 unittest 在作为道具传递的函数上失败
【发布时间】:2018-08-09 00:40:42
【问题描述】:

我正在尝试为一个简单的组件编写单元测试。

这是我的组件:

const ErrorWrpper = (props) =>(
<div className={props.class} style={props.validateForm(props.inputType)?
{display: 'none'}:{}}>
<span>{props.message}</span></div>
)
 export default  ErrorWrpper;

这是我的测试:

import React from 'react';
import { expect } from '../../test_helper';
import { shallow } from 'enzyme';
import { it, describe, beforeEach } from 'mocha';
import  ErrorWrapper  from '../../../src/app/components/login/ErrorWrapper';

let errorWrapper;
describe("ErrorWrapper component unit tests", () => {
 function validateForm(test){

}
before(() => {

    errorWrapper = shallow(<ErrorWrapper class="test"  inputType="all" validateForm={this.validateForm}/>);
});


// these tests check that each className that should exist, exists
describe("className check", () => {
    it('should have className test', () => {
        expect(errorWrapper.find('test')).to.exist;
    });
})
})

现在当我运行它时,我得到了这个:

ErrorWrapper component unit tests "before all" hook:
 TypeError: Cannot read property 'validateForm' of undefined

如您所见,我正在尝试将 validateError 函数作为道具提供,但我仍然收到错误消息。有什么想法吗?

【问题讨论】:

    标签: reactjs chai enzyme chai-enzyme


    【解决方案1】:

    不清楚您为什么在测试组件实例化中使用this应该可以工作:

    errorWrapper = shallow(<ErrorWrapper class="test" inputType="all" validateForm={validateForm} />);
    

    另外,您的组件中有一个错字:ErrorWrpperErrorWrapper,对吧? 您也没有将 message 属性传递给它。

    【讨论】:

      【解决方案2】:

      看起来您在 before all 钩子中没有得到对 this 的引用。尝试使用箭头函数来定义您的 validateForm 函数,以便它会自动将其与 this 引用绑定,或者您需要手动绑定 validateForm 函数,如 this.validateForm.bind(this)

      【讨论】:

        猜你喜欢
        • 2019-11-13
        • 2020-11-19
        • 1970-01-01
        • 1970-01-01
        • 2020-08-09
        • 1970-01-01
        • 2017-05-09
        • 2019-08-06
        • 2019-07-03
        相关资源
        最近更新 更多