【发布时间】:2017-06-30 12:54:09
【问题描述】:
我最近不得不修复一个在工作中使用旧的 react 组件的错误。通常在修复错误时,我们会用它编写测试。问题是,react 组件从服务器异步获取(我可以重构代码,以便将异步操作移动到 redux 中,但我们不将重构作为错误修复的一部分)所以在测试组件是什么时应该渲染,我必须等待500ms 才能让承诺解决。
我知道如果我创建组件的实例并直接调用该方法,我就不必执行 setTimeout,我可以只执行 .then,但我们喜欢测试组件的输入/输出而不调用内部方法。
有没有比设置超时更优雅的解决方案?这是当前代码:
it('autofills and locks all the fields where user data is present', function(done) {
const emailInput = $wrapper.find('#email');
emailInput.value = 'email@example.com';
emailInput.simulate('blur');
// - autofill does an async request
// - we need to wait for the promise to resolve before
// checking if the inputs are disabled or not
setTimeout(() => {
const identifierInput = $wrapper.find('#id');
const lastNameInput = $wrapper.find('#last-name');
const phoneNumberInput = $wrapper.find('#phone-number');
const firstNameInput = $wrapper.find('#first-name');
expect(firstNameInput.html().includes('disabled')).to.be.true;
expect(lastNameInput.html().includes('disabled')).to.be.true;
expect(phoneNumberInput.html().includes('disabled')).to.be.true;
expect(identifierInput.html().includes('disabled')).to.be.true;
done();
}, 500);
});
【问题讨论】:
标签: javascript mocha.js enzyme