2017-07-21 79 views
0

我有一個React組件,我試圖測試它的一些實例方法,但我無法理解我應該如何執行它。這使我感到沮喪的事實是,我指的是this.setState()在測試中,還有event.target,它們在我的測試中處於不同的上下文中,因此返回爲undefined。處理這個問題的正確方法是什麼?如何測試React組件類方法

這裏是我的組件:

export default class MessageForm extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { 
     message: '', 
    }; 
    } 

    onChange(event) { // testing this method 
    const message = event.target.value; // event is undefined 
    this.setState(prevState => Object.assign({}, prevState, { message })); // 'this' is undefined 
    } 

    handleOnClick(event) { 
    event.preventDefault(); 
    // do some stuff here 
    } 

    render() { 
    return (
     <Form action="post"> 
     <TextArea onChange={this.onChange} /> 
     <ExpireButtonGroup /> 
     <SubmitButton onClick={this.handleOnClick}> 
      <LockIcon src={lock} /> 
      Save 
     </SubmitButton> 
     </Form> 
    ); 
    } 
} 

我使用玩笑和酶進行測試。我可以用這個測試來觸發的方法:

test('it should allow a message to be typed',() => { 
    const messageForm = shallow(<MessageForm />); 
    expect(messageForm.instance().onChange()) 
    }); 

----------- -----------編輯

我發現這問題:How to mock React component methods with jest and enzyme ...這似乎有幫助,但我仍然堅持錯誤cannot read property 'target' of undefined。這是我的新測試:

test('it should handle a click event',() => { 
    const mockEvent = { 
     target: { dataset: { value: '60' }} 
    }; 
    const button = shallow(<ExpireButton value={40}>Save</ExpireButton>); 
    button.instance().handleOnClick(mockEvent) = jest.fn(); 
    button.update(); 
    button.simulate('click'); 
    expect(button.handleOnClick).toBeCalled(); 
    }); 
}); 

回答

1

你幾乎做到了。在實例中根據需要發送參數。

test('it should allow a message to be typed',() => { 
const messageForm = shallow(<MessageForm />); 
expect(messageForm.instance().onChange({target:"any text you want"})) 
}); 
+0

感謝您的幫助!我發現我可以通過params,但仍然不能讓我進行有效的測試,因爲我的「expect」並不能真正測試任何東西。我相信我已經取得了進展,但我還沒有。我用更多的調查結果更新了我的問題。 – dericcain

+0

當您調用.instance()方法時,您只是說測試調用該方法。所以,你總是必須通過參數。這將幫助你測試MessageForm組件,也就是在onChange道具被調用之後;組件是否正常工作。爲了確保測試是正確的,在爲