我正在尝试为一个写的简单组件编写单元测试。
这是我的组件:
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函数作为道具提供,但我仍然得到错误。任何的想法?
目前尚不清楚为什么在测试组件实例化中使用this
。这应该工作:
errorWrapper = shallow(<ErrorWrapper class="test" inputType="all" validateForm={validateForm} />);
此外,你的组件中有一个拼写错误:ErrorWrpper
是ErrorWrapper
,对吗?你也没有把它传给message
道具。
看起来你没有在你之前的钩子中获得this
的引用。尝试使用箭头函数来定义你的validateForm
函数,这样它就会用this
引用自动绑定它,或者你需要手动绑定validateForm
函数,如this.validateForm.bind(this)
。