2017-10-13 171 views
0

我是新来TDD和我想测试我的回调函数在我的年龄组成: 我Age.js文件如下:在ReactJS中使用jest和酶测试回调函数?

import React, { Component } from "react"; 
import { connect } from "react-redux"; 
import actions from "../../actions"; 
import TextFieldComponent from "../Module/TextFieldComponent"; 

export class Age extends Component { 

    ageValueCallBack = age => { 
    console.log("value is : ", age); 
    this.props.selectAgeAction(age) 
    }; 

    render() { 
    const props = { 
     onChange: this.ageValueCallBack, 
     hintText : 'Eg. 25', 
     floatingLabelText: "Age(Years)", 
     value : (this.props.usersData) ? this.props.usersData.basic.age : null 
    }; 
    return <TextFieldComponent {...props} />; 
    } 
} 

function mapStateToProps({ usersData }) { 
    return { 
    usersData 
    }; 
} 

export default connect(mapStateToProps, { 
    selectAgeAction: actions.selectAgeValue 
})(Age); 

TextFieldComponent跟随其中:

import TextField from "material-ui/TextField"; 

const TextFieldComponent = props => { 
    return (
    <TextField 
     onChange={(event, string) => { 
     props.onChange(string) 
     }} 
     floatingLabelText={props.floatingLabelText || "floatingLabelText"} 
     value={props.value || null} 
     hintText={props.hintText || "hintText will be here"} 
     autoFocus ={true || props.autoFocus} 
    /> 
); 
}; 

我想测试ageValueCallBack年龄组件的功能,但我没有得到任何特定的方法到达那里。

任何见解都会有所帮助。

谢谢..

+0

你所要做的是,你需要一个间谍,sinonJs有利于这项工作。 所以当你渲染Age组件时,prop selectAgeAction =“the sinon spy”。 你也需要在你的TextField上做一个onChangeEvent,然后声明对抗sinon间谍。 http://sinonjs.org/releases/v4.0.1/spies/ –

回答

2

随着酶可以触发使用simulate('change', {}, 'someString')TextFieldComponentonChange事件。该selectAgeActionAge.js需要与jest.fn()创建的间谍:

const selectAgeAction = jest.fn() 
const component = shallow(<Age selectAgeAction={selectAgeAction} />) 
component.find('TextField').simulate('change', {}, '10') 
expect(selectAgeAction).toHaveBeenCalledWith('10')