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

时间:2019-07-05 22:52:10

标签: javascript mocha assert

据我了解,测试套件中it调用的执行是顺序发生的,即一个调用直到前一个调用完成才执行。但是,我看到的行为令人讨厌,即在执行第一个请求的回调之前执行第二个请求的回调

我不知道我的前提是否错误(正如IRC中的某些人所说,表明it调用应该彼此独立并且可以并行执行)还是我的实现存在某种缺陷< / p>

我的问题:如果我想测试与机器人的对话(在发出另一个请求之前,我需要在服务器上等待服务器的响应),我可以通过一系列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');
})

在这种情况下,由于会话可能很长,我需要大幅增加超时时间?

1 个答案:

答案 0 :(得分:1)

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

  })

})
相关问题