对于作为道具传递的函数,reactjs组件的unittest失败

问题描述 投票:1回答:2

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

这是我的组件:

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
2个回答
1
投票

目前尚不清楚为什么在测试组件实例化中使用this。这应该工作:

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

此外,你的组件中有一个拼写错误:ErrorWrpperErrorWrapper,对吗?你也没有把它传给message道具。


0
投票

看起来你没有在你之前的钩子中获得this的引用。尝试使用箭头函数来定义你的validateForm函数,这样它就会用this引用自动绑定它,或者你需要手动绑定validateForm函数,如this.validateForm.bind(this)

© www.soinside.com 2019 - 2024. All rights reserved.