如何在React ES6类中测试箭头函数

Leo*_*ieh 7 testing reactjs arrow-functions

我在我的React组件中使用了箭头函数来避免绑定这个上下文,例如我的组件看起来像这样;

class Comp extends Component {
   _fn1 = () => {}
   _fn2 = () => {}
   render() {
      return (<div></div>);
   }
}
Run Code Online (Sandbox Code Playgroud)

如何在我的测试用例中测试_fn1_fn2运行?因为这些功能与React组件本身无关,所以当我这样做时

 fnStub = sandbox.stub(Comp.prototype, "_fn1");
Run Code Online (Sandbox Code Playgroud)

它不起作用,因为_fn没有绑定Comp.prototype.因此,如果我想用箭头语法创建函数,我如何在React中测试这些函数?谢谢!

Ale*_*ung 0

一般来说,我发现测试这些函数是否已产生正确的组件状态比测试函数本身更容易。例如,下面是一个在单击按钮时切换状态变量的组件:

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>
      );
   }
}
Run Code Online (Sandbox Code Playgroud)

我在这里的首选方法是将组件作为一个整体进行测试,即单元测试的“单元”是组件。因此,测试将找到按钮,模拟单击,并确保显示正确的文本。这可能不是教科书上的单元测试,但它达到了测试组件的目的。

使用 sinon/chai/mocha/enzyme:

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');
    });
});
Run Code Online (Sandbox Code Playgroud)