gpt4 book ai didi

javascript - describe() 中的 it() 调用是否同步执行?

转载 作者:行者123 更新时间:2023-12-02 23:21:59 24 4
gpt4 key购买 nike

据我了解,测试套件中的 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() 回调被调用并引发(或不引发)异常。只要未处理的 promise 拒绝,这可能会或可能不会显示在控制台中。

您可以使用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');
})

})

这些测试相互依赖吗?测试应该是独立的。如果您尝试测试协议(protocol)握手,您可能需要执行以下操作:

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');

})

})

关于javascript - describe() 中的 it() 调用是否同步执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56909947/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com