How to test arrow function in React ES6 class

I used the arrow function inside my React component to avoid linking this context, for example, my component looks like this:

class Comp extends Component {
   _fn1 = () => {}
   _fn2 = () => {}
   render() {
      return (<div></div>);
   }
}

How to check the function _fn1and _fn2in my test cases? Since such a function was not related to the React component, so when I do

 fnStub = sandbox.stub(Comp.prototype, "_fn1");

it does not work because it _fndoes not contact Comp.prototype. Thus, how can I test these functions in React if I want to create a function with arrow syntax? Thank!

+4
source share
1 answer

, , , . , , :

class MyComponent extends Component {
    state = {
        toggle: false
    }

   _fn1 = () => {
       this.setState(previousState => ({
           toggle: !previousState.toggle
       });
   }

   render() {
      const { toggle } = this.state;

      return (
          <button onClick={this.clickHandler}>
              Turn me {toggle ? 'on' : 'off'}
          </button>
      );
   }
}

, .. "" unit test . , , . unit test, .

///:

describe('My Component', () => {
    it('alternates text display when the button is clicked', () => {
        const wrapper = shallow(<MyComponent />);

        expect(wrapper).to.have.text('Turn me off');

        wrapper.find('button').simulate('click');

        expect(wrapper).to.have.text('Turn me on');
    });
});
0

All Articles