2017-10-13 72 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') 
相關問題