我正在为一个基于Promise的函数编写一个测试。具体来说,它是一个React组件&我正在测试以确保onChange处理程序被正确调用。
我的组件如下:
class TextInput extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.value || '',
};
this.onChange = this.onChange.bind(this);
}
updateState(values) {
return new Promise(
(resolve) => {
this.setState(values, () => { resolve(this.state); });
}
);
}
onChange(event) {
this.updateState({ value: event.target.value })
// then fire the onChange handler (if necessary)
//
.then((state) => {
if (this.props.onChange) {
// console.log(this.props.onChange) shows that this IS a
// Sinon spy function
this.props.onChange(state.value);
}
})
.catch((err) => { console.log('-----------', err); });
}
render() {
// render the component (omitted to keep this short)
}
}
我的测试是这样的:
import React from 'react';
import { mount } from 'enzyme';
import chai from 'chai';
import sinon from 'sinon';
import TextInput from '../../../../client/modules/components/TextInput';
const expect = chai.expect;
describe('TextInput component editing', () => {
it('calls the onChange handler', () => {
const onchange = sinon.spy();
const value = '';
const editedValue = 'something';
const component = mount(<TextInput value={value} onChange={onchange} />);
// change the value
//
component.find('input').simulate('change', {
target: { value: editedValue }
});
expect(component.find('input').prop('value')).to.equal(editedValue);
expect(onchange.calledOnce).to.equal(true);
expect(onchange.calledWith(editedValue)).to.equal(true);
});
});
最后两次expect
调用的测试失败。
如果我用一个简单的旧函数替换sinon spy,这个函数就是调用的。例如,
// instead of this...
// const onchange = sinon.spy();
// do this...
const onchange = (value) => { console.log(`VALUE = ${value}`); };
如果我直接使用setState
方法的回调,它会起作用。例如,
// instead of...
// this.updateState(values).then(...)
// do this...
this.setState(values, () => {
// call the onChange handler...
});
我可以这样做,但我想避免它,因为我将向这个组件添加更多的功能,我不想被困在末日的金字塔中。
起初,我认为这可能与updateState
方法范围内的this
或该方法中的一个回调函数的问题有关,但添加console.log
语句表明,this
在所有适当的位置都引用了TextInput
的实例。
在onChange
处理程序被触发之前添加一个console.log
语句来转储它,这表明this.props.onChange
实际上是一个Sinon间谍。
我看过其他包,比如承诺的sinon,但我不认为这个包真的能解决我想要做的事情——我只想确保我的回调是在promise then
子句中调用的。sinon-as-promised
是一个用来截断整个承诺的包。
我可能忽略了一些简单的东西,但不管是什么,我都看不到。
在执行对状态的异步调用之前,同步测试似乎已经完成。我不会评论是否应该同时设置状态和调用更改方法以及何时进行。但我认为您目前的简单答案是通过传递done
参数来使用异步测试。(很明显,在那一点上,你甚至不需要间谍,但我把它留在这里只是为了表明它本身并不是不起作用的间谍:
describe('TextInput component editing', () => {
it('calls the onChange handler', done => {
const fakeOnChange = stuff => {
expect(spyOnChange.calledOnce).to.equal(true);
expect(editedValue).to.equal(stuff);
expect(component.find('input').prop('value')).to.equal(editedValue);
done();
}
const spyOnChange = sinon.spy(fakeOnChange);
const value = '';
const editedValue = 'something';
const component = mount(<TextInput value={value} onChange={spyOnChange} />);
component.find('input').simulate('change', {
target: { value: editedValue }
});
});
});