2017-08-18 33 views
0

有三件事我想弄清楚。现在我正在使用浅层渲染。我使用Enzyme和Jest。浅试React branch Jest and Enzyme

  1. 我想知道如何测试我的React组件中的分支。 I 想测试if-else语句(?:)的两侧。而且我不想用自己的功能把它拉出来。
  2. 如何在输入更改时检查this.props.myFuncFromProps(value)是否被称为 ?
  3. 什么是测试mapStateToProps和 mapDispatchToProps的最佳实践?

这里是我的组件会是什么样子的例子:

import React from 'react'; 
 
import MyChildComponent from 'wherever'; // This component is an input field in this example 
 

 
export class MyComponent extends React.Component { 
 
    render() { 
 
    const myFunc(value) { 
 
     this.props.myFuncFromProps(value); 
 
    } 
 
    
 
    return (
 
     <div> 
 
     { this.props.isTrue ? 
 
      <MyChildComponent 
 
      value={this.props.value} 
 
      onChange={(value) => myFunc(value)} 
 
      /> 
 
      : null 
 
     } 
 
     </div> 
 
    ); 
 
    } 
 
}

回答

0

为了测试不同状态正好与不同的属性使您的组件,并进行快照(注,您必须在第一次检查快照时进行检查)。要测试事件回调,您必须将间谍功能(jest.fn())传递到组件,并使用simulate来调用事件,然后测试间谍是否被调用。

describe('MyComponent',() => { 
    describe('with isTrue is true',() => { 
     let myComponent 
     let myFuncFromProps 
     beforeEach(() => { 
      myFuncFromProps = jest.fn() 
      myComponent = shallow(
       <MyComponent isTrue myFuncFromProps={myFuncFromProps} /> 
      ) 
     }) 
     it('renders correct',() => { 
      expect(myComponent).matchSnapshot() 
     }) 

     it('onchange will call myFuncFromProps',() => { 
      myComponent 
       .find('MyChildComponent') 
       .simulate('onChange', 'someValue') 
      expect(myFuncFromProps).toHaveBeenCalledWith('someValue') 
     }) 
    }) 

    it('with isTrue is false it renders correct',() => { 
     const myComponent = shallow(<MyComponent />) 
     expect(myComponent).matchSnapshot() 
    }) 
}) 
相关问题