代码之家  ›  专栏  ›  技术社区  ›  Hamed Minaee

reactjs组件的unittest在作为道具传递的函数上失败

  •  1
  • Hamed Minaee  · 技术社区  · 7 年前

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

    这是我的组件:

    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函数作为道具提供给您,但仍然出现了错误。有什么想法吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   Miguel Calderón    7 年前

    不清楚你为什么要使用 this 在测试组件实例化中。 应工作:

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

    此外,组件中还有一个拼写错误: ErrorWrpper ErrorWrapper 正当 你也没有通过 message 道具

        2
  •  0
  •   Pathik Mehta    7 年前

    看起来你没有得到 this 在你的面前,所有钩。尝试使用箭头函数定义 validateForm 使其自动绑定 引用或需要绑定 验证窗体 手动操作,如 this.validateForm.bind(this) .