首页 > 解决方案 > 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');
})

在这种情况下,我需要大幅增加超时时间,因为对话可能很长?

标签: javascriptmocha.jsassert

解决方案


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

  })

})

推荐阅读