javascript - describe() 中的 it() 调用是否同步执行?
问题描述
我的理解是it
测试套件中调用的执行顺序发生,即一个调用在前一个调用完成之前不会执行。但是,我看到了令人不快的行为,即在第一个请求的回调完成之前执行第二个请求的回调
我不知道我的前提是错误的(正如 IRC 上的一些人所说,表明it
调用应该相互独立并且可以并行执行)或者我的实现存在某种缺陷
我的问题:如果我想测试与机器人的对话(在发出另一个请求之前我需要等待服务器的响应),我可以通过一系列it
调用来完成吗?有点像:
describe('conversation', () => {
it('begins chat', () => {
fetch(server + '?hello').then(res => {
assert.equal(res, 'EHLO');
})
})
it('login request', () => {
fetch(server + '?login=xxx').then(res => {
assert.equal(res, 'User logged in');
})
})
it('get headers', () => {
fetch(server + '?headers').then(res => {
assert.equal(res, '0 xxx xxxx');
})
})
})
还是我需要做类似的事情:
it('conversation', async () => {
var res = await fetch(server + '?hello')
assert.equal(res, 'EHLO');
res = await fetch(server + '?login=xxx')
assert.equal(res, 'User logged in');
res = await fetch(server + '?headers')
assert.equal(res, '0 xxx xxxx');
})
在这种情况下,我需要大幅增加超时时间,因为对话可能很长?
解决方案
fetch()
是异步的。当回调启动操作并返回时,您的测试将始终成功。在稍后的事件循环中,调用操作的回调并抛出异常(或不抛出异常)。只要未处理的承诺拒绝,这可能会或可能不会出现在控制台中。it()
fetch()
fetch()
.then()
你可以使用chai-with-promises
. 或者,更简单的是,使用 async/await:
describe('conversation', () => {
it('begins chat', async () => {
const res = await fetch(server + '?hello');
assert.equal(res, 'EHLO');
});
it('login request', async () => {
const res = await fetch(server + '?login=xxx')
assert.equal(res, 'User logged in');
})
it('get headers', async () => {
const await fetch(server + '?headers');
assert.equal(res, '0 xxx xxxx');
})
})
这些测试是否相互依赖?测试应该是独立的。如果您正在尝试测试协议握手,您可能需要执行以下操作:
describe('conversation', () => {
it('does the expected', async () => {
let res;
res = await fetch(server + '?hello')
assert.equal(res, 'EHLO');
res = await fetch(server + '?login=xxx') )
assert.equal(res, 'User logged in');
res = await fetch(server + '?headers') )
assert.equal(res, '0 xxx xxxx');
})
})
推荐阅读
- jquery - 如何根据某些特定数据对jquery花式框数据中的数据进行排序
- sql - CREATE TABLE 中的 DEFAULT 上的“缺少右括号”
- python - 如何从熊猫数据框中获取特定行?
- python - 检查是否分配或调用函数
- javascript - PhaserJS:动画对象在动画期间退出并重新出现
- python - 考虑到组应该通过其值的平均值来平衡,有没有办法从数据框中创建组?
- powershell - -WhatIf 输出与实际结果不匹配
- javascript - 错误边界应该实现 getDerivedStateFromError()
- macos - 在 macos 上调试 .NET - 缺少 libsosplugin.so
- android - 未调用活动