Javascript 如何测试一种方法叫一次酶法
我想测试我的handleChange函数,它是由下拉菜单中的onChange事件触发的。以下是该菜单的反应结构Javascript 如何测试一种方法叫一次酶法,javascript,reactjs,unit-testing,enzyme,Javascript,Reactjs,Unit Testing,Enzyme,我想测试我的handleChange函数,它是由下拉菜单中的onChange事件触发的。以下是该菜单的反应结构 class StationNavigationBar extends React.Component { handleChange = (event, index, value) => { this.props.onStationChange(value); } render() { return ( <DropDownMenu value={thi
class StationNavigationBar extends React.Component {
handleChange = (event, index, value) => {
this.props.onStationChange(value);
}
render() {
return (
<DropDownMenu value={this.props.initial} onChange={this.handleChange}>
{ this.props.stations.map((station, index) =>
<MenuItem key={station.id} value={station.id} primaryText={station.name} />
)}
</DropDownMenu>
);
}
}
class StationNavigationBar扩展了React.Component{
handleChange=(事件、索引、值)=>{
此.props.onStationChange(值);
}
render(){
返回(
{this.props.stations.map((station,index)=>
)}
);
}
}
我试图使用Ezyme来监视handleChange函数,但是spy函数似乎无法检测onChange事件,下面是我当前的测试代码
describe("when `dropDownMenu` is changed", () => {
it("onStationChange should be called", () => {
let props = {
initial: 'Something',
title: 'something',
onStationChange: ()=>{},
onLogOut: ()=>{},
stations: [{
id: '1',
name: "Station 2" },
{ id: '2',
name: "Station 3" },
{ id: '3',
name: 'Station 4'}]
};
const stationNavigationBar = shallow(<StationNavigationBar {...props} />);
const instance = stationNavigationBar.instance();
const goSpy = sinon.spy(instance, 'handleChange');
stationNavigationBar.update();
const toolbarGroup = stationNavigationBar.find('ToolbarGroup');
const dropDownMenu = toolbarGroup.find('DropDownMenu');
dropDownMenu.simulate('change');
expect(goSpy.calledOnce).toBe(true);
});
});
description(“当'dropDownMenu'更改时,()=>{
它(“应调用onStationChange”,()=>{
让道具={
首字母:'某物',
标题:“某物”,
onStationChange:()=>{},
onLogOut:()=>{},
电台:[{
id:'1',
名称:“2号站”},
{id:'2',
名称:“3号站”},
{id:'3',
名称:'站4'}]
};
const stationNavigationBar=shallow();
const instance=stationNavigationBar.instance();
const goSpy=sinon.spy(例如,“handleChange”);
stationNavigationBar.update();
const toolbarGroup=stationNavigationBar.find('toolbarGroup');
const dropDownMenu=toolbarGroup.find('dropDownMenu');
dropDownMenu.simulate('change');
expect(goSpy.calledOnce).toBe(true);
});
});
有什么我没注意的地方吗?我在测试用例中遗漏了什么部分。创建一个spy方法,并将spy作为
onStationChange
属性传递
const onStationChange = sinon.spy();
const props = {
initial: 'Something',
title: 'something',
onStationChange,
//...
};
创建一个spy方法,并将spy作为
onStationChange
prop传递
const onStationChange = sinon.spy();
const props = {
initial: 'Something',
title: 'something',
onStationChange,
//...
};
@Oridori,sinon我应该把这部分放在哪里,我想在我的代码中我有const goSpy=sinon.spy(例如,“handleChange”)already@OriDrori,sinon我应该把那部分放在哪里,我想在我的代码中我已经有const goSpy=sinon.spy(例如,'handleChange')