簡體   English   中英

使用superagent +的Mocha測試承諾超時而不是因“期望”而失敗

[英]Mocha tests using superagent + promises timeout rather than fail with 'expect'

我正在使用mocha對外部Web服務運行許多集成測試。 我將superagent-promise用於請求/響應處理,並且將expect作為我的斷言庫。

對於其中的某些測試,我需要將大量請求鏈接在一起,因此,諾言很有幫助。 但是我注意到我的測試現在由於超時(並且沒有錯誤消息)而不是錯誤消息本身而失敗。 作為一個簡單的例子:

  it('[MESSAGES-1] cannot be posted without an auth token', function(done) {
    agent.post(config.webRoot + '/rooms/ABC/messages').send({
      content: 'This is a test!'
    }).end().then(function(res) {
      // Not expected
    }, function(err) {
      expect(err.status).toBe(401)
      done()
    })
  })

可以正常工作並通過:

  Messages
    ✓ [MESSAGES-1] cannot be posted without an auth token

但是,如果我更改斷言以期望使用不同的狀態代碼:

expect(err.status).toBe(200) // This should fail

然后測試失敗並超時!

  1) Messages [MESSAGES-1] cannot be posted without an auth token:
     Error: timeout of 1000ms exceeded. Ensure the done() callback is being called in this test.

這是個常見的問題嗎? 有什么解決方法或可以調整的地方嗎? 我不想失去使用諾言的能力。

這是一個已知的問題?

這實際上不是問題。

問題在於expect(err.status).toBe(200)引發了一個錯誤,該錯誤被expect(err.status).toBe(200)內部吞沒.then並導致代碼永不到達done() 您應該將代碼重組為以下內容:

it('[MESSAGES-1] cannot be posted without an auth token', function(done) {
    agent.post(config.webRoot + '/rooms/ABC/messages').send({
      content: 'This is a test!'
    }).end()

    .then(function(res) {
      // Not expected
    }, function(err) {
      expect(err.status).toBe(401)
      done()
    })
    .catch(function(err) {
        done(err); //report error thrown in .then
    })
  })

這樣,您就可以捕獲並報告expect(err.status).toBe(200)引發的錯誤。

在您的情況下,發生超時是因為從未調用完回調,因為http請求沒有失敗,或者期望失敗了,所以引發了斷言錯誤。

Mocha處理正確的(承諾返回的)異步測試,因此不要使用完成的回調,它在與promise混合時會引起混亂。 返回諾言:

it('[MESSAGES-1] cannot be posted without an auth token', function() {
  return agent.post(config.webRoot + '/rooms/ABC/messages').send({
    content: 'This is a test!'
  }).end().then(function(res) {
    // here you must throw an error, because if the post didnt fail somehow, the test would be green because of no assertations and no promise rejection.
    throw new Error("Not expected");
  }, function(err) {
    expect(err.status).toBe(401);
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM