Javascript 如何在异步React组件中正确测试去抖动功能?
我的react组件运行一个异步查询来获取一些数据,因为用户输入可能导致重新查询,我希望对查询进行评级限制,然后使用返回的结果设置组件的状态 MyComponent(反应成分) 目前,我正在删除我的主要api出口点,该出口点通过Javascript 如何在异步React组件中正确测试去抖动功能?,javascript,reactjs,asynchronous,mocha.js,enzyme,Javascript,Reactjs,Asynchronous,Mocha.js,Enzyme,我的react组件运行一个异步查询来获取一些数据,因为用户输入可能导致重新查询,我希望对查询进行评级限制,然后使用返回的结果设置组件的状态 MyComponent(反应成分) 目前,我正在删除我的主要api出口点,该出口点通过sinon stub promise包退出并获取返回承诺的数据 before((done) => { stub = stubGlobalFn('evaluate'); // returns stubbed promise, uses npm:sinon-stub-
sinon stub promise
包退出并获取返回承诺的数据
before((done) => {
stub = stubGlobalFn('evaluate'); // returns stubbed promise, uses npm:sinon-stub-promise
});
这使我能够使用自定义读取器(在别处测试)读取模拟响应,然后出于测试目的同步解析它
mytest.spec.jsx
let stub;
const testWithProps = props => (
new Promise((resolve, reject) => {
new Reader(histories).readGrid((err, grid) => {
try {
expect(err).to.be.a('null');
stub.resolves(grid);
// ....
然后,在相同的testWithProps
功能中,我能够使用我在测试中指定为某种测试工厂的props挂载表
组件
const wrapper = mount(<Table {...props} />);
如果我想在异步行为之后测试组件的状态,我应该在react组件中插入处理程序函数吗?我甚至不知道如果那是需要的话,该如何删掉那部分
最终,我的测试结果如下所示:
it('toggles the row for the value when clicked', () => {
const props = {
// some props that I use
};
return testWithProps(props).then((wrapper) => {
// simply testing that my mocked response made it in successfully to the rendered component
expect(wrapper.state().results.length).to.equal(4);
});
});
stub.thenable.then(() => {
// --------------------------
// PROBLEM: how to test without setting a timeout?
// --------------------------
setTimeout(() => {
resolve(wrapper.update());
}, 200);
// --------------------------
// --------------------------
});
it('toggles the row for the value when clicked', () => {
const props = {
// some props that I use
};
return testWithProps(props).then((wrapper) => {
// simply testing that my mocked response made it in successfully to the rendered component
expect(wrapper.state().results.length).to.equal(4);
});
});