1

I am trying to write a unit test for a simple component that wrote.

Here is my component:

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

And here is my test:

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;
    });
})
})

Now when I run it I get this:

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

As you see I am trying to feed validateError function as props but still I am getting the error. Any idea?

Hamed Minaee
  • 2,480
  • 4
  • 35
  • 63

2 Answers2

1

It's not clear why are you using this at all in your test component instantiation. This should work:

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

Also, there's a typo in your component: ErrorWrpper is ErrorWrapper, right? You're also not passing it the message prop.

Miguel Calderón
  • 3,001
  • 1
  • 16
  • 18
0

Looks like you are not getting the reference to this in your before all hook. Try to use arrow function to define your validateForm function so it will auto bind it with this reference or you need to bind validateForm function manually like this.validateForm.bind(this).

Pathik Mehta
  • 401
  • 4
  • 9