2016-11-21 88 views
2

我使用Jest v16.0.1,react-test-renderer v15.4.0和react-addons-test-utils v15.4.0測試React組件。React測試渲染器模擬點擊元素

組件已經呈現一個按鈕:

<button 
    type="button" 
    className="btn btn-lg btn-primary btn-danger" 
    disabled={this.state.cancelButtonDisabled} 
    onClick={() => this.handleCancel()} 
    ref="cancelButton" 
>Cancel</button>); 

而且在我的測試,我的渲染,像這樣的組件:

const component = renderer.create(
    <MyComponent /> 
); 

const instance = component.getInstance(); 
// This works but is ugly 
component.toJSON().children[1].children[0].props.onClick(); 
// This doesn't work 
ReactTestUtils.Simulate.click(instance.refs.cancelButton); 

let tree = component.toJSON(); 
expect(tree).toMatchSnapshot(); 

什麼是模擬這個按鈕點擊的推薦方法?您可以遍歷該組件的JSON表示,但似乎應該是更好的方法。

之前,當我使用ReactTestUtils.renderIntoDocument你可以通過在使用裁判組件的引用到ReactTestUtils.Simulate.click

我已經看到了這個問題 - How to interact with components rendered by ReactTestRenderer/Jest但我認爲該API已經改變了我的組件實例沒有find()方法。

回答

1

也許已經太遲了,但是find是來自酶的API。你提到的問題的答案就像評論中提到的一樣。

這樣的事情應該工作。

MyComponent.jsx

import React from 'react'; 

class MyComponent extends React.Component { 
    constructor() { 
    super(); 
    this.state = { 
     cancelButtonDisabled: false, 
    }; 
    } 
    handleCancel() { 
    this.props.cancelAction(); 
    } 
    render() { 
    return (
     <button 
     type="button" 
     className="btn btn-lg btn-primary btn-danger" 
     disabled={this.state.cancelButtonDisabled} 
     onClick={() => this.handleCancel()} 
     ref="cancelButton" 
     > 
     Cancel 
     </button> 
    ); 
    } 
} 

export default MyComponent; 

MyComponent.test.jsx

import React from 'react'; 
import {mount} from 'enzyme'; 
import MyComponent from './MyComponent'; 

describe('Test MyComponent',() => { 
    it('should be able to click the button',() => { 
    const mockFunction = jest.fn(); 
    const element = mount(<MyComponent cancelAction={mockFunction} />); 
    element.find('button').simulate('click'); 
    expect(mockFunction).toHaveBeenCalled(); 
    }); 
}); 

沒有酶,它是這樣的。

MyComponentWithoutEnzyme.test.jsx

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import ReactTestUtils from 'react-addons-test-utils'; 
import MyComponent from './MyComponent'; 

describe('Test MyComponent',() => { 
    it('should be able to click the button',() => { 
    const mockFunction = jest.fn(); 
    const element = ReactTestUtils.renderIntoDocument(
     <MyComponent cancelAction={mockFunction} />, 
    ); 
    const button = ReactDOM.findDOMNode(element); 
    ReactTestUtils.Simulate.click(button); 
    expect(mockFunction).toHaveBeenCalled(); 
    }); 
});