我正在学习 TDD React here不明白下面的测试情况:
it('Correctly updates the state after AJAX call in `componentDidMount` was made', (done) => {
nock('https://api.github.com')
.get('/users')
.reply(200, [
{ 'name': 'Reign', 'age': 26 }
]);
// Overwrite, so we can correctly reason about the count number
// Don't want shared state
wrapper = mount(<UsersListComponent />);
setTimeout(function() {
expect(wrapper.state().usersList).to.be.instanceof(Array);
expect(wrapper.state().usersList.length).to.equal(1);
expect(wrapper.state().usersList[0].name).to.equal('Reign');
expect(wrapper.state().usersList[0].age).to.equal(26);
nock.cleanAll();
done();
}, 1500);
});
使用nock
伪造请求的目的是什么?此请求不执行任何操作,我不确定响应的去向。我认为 TDD 方法是编写测试(代码从 wrapper 开始),看到它失败,然后在实际组件中使用真正的 ajax 调用来测试。我不明白 nock 在这里做什么。
最佳答案
在您的代码中调用 nock
的目的是伪造 API 请求。 Nock 捕获/拦截调用,而不是实际响应,它返回带有虚假信息的响应。
测试的题目是Correctly updates the state after AJAX call...
所以目的是测试状态是否正确更新,而不是实际的API请求是否已经成功承载出去。
这使您可以对不同的场景进行建模和测试,例如,您的应用在接收不同数据集时的行为方式。它还允许您在实际 API 可能尚未准备就绪时完成测试。
关于javascript - 在测试中使用模拟 ajax 调用的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39868474/