在描述()中呼叫()同步执行



我的理解是,在测试套件中执行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。或者,更容易的是使用异步/等待:

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

最新更新