2017-08-18 30 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() 
    }) 
}) 
相關問題