簡體   English   中英

帶有 Nock 的 Mocha Chai:為什么在“after()”和“afterEach()”中進行清理時會出現超時錯誤?

[英]Mocha Chai with Nock: why am I getting timeout errors when doing cleanup in 'after()' and 'afterEach()'?

我在 mocha/chai 套件中使用 Nock 存根(嘲笑?)一個 fetch 請求,它似乎工作正常。 但是,當我想在describe后清理並將事情恢復正常時,我正在做 nock 存根,我收到 mocha 超時錯誤。

我的 nock 設置(我將在每個it之前執行此操作,使用不同的 URL,現在我只為一個執行此操作)是

it('should succeed for correct nickname, move and gameID with game in progress', () =>
      Promise.resolve()
        .then(_ => {
          nock('http://localhost:8080')
            .post(`/api/user/${nickname}/game/${gameInProgress.id}`)
            .reply(200, {
              message: 'successful move'
            })
          return logic.makeAGameMove(nickname, nickname2, {from: "e2", to: "e4", promotion: "q"}, gameInProgress.id, token)
        })
      .then(res => {
        const {message} = res
        expect(message).to.equal('successful move')
      })

describe的最后我有

 afterEach(_=> nock.cleanAll())
 after(_=> nock.restore())

但我不斷收到以下錯誤

        "after each" hook for "should succeed for correct nickname, move and gameID with game in progress":
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. 
  "after all" hook:
     Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.

我有點不知所措。 我什至試圖在 Promises 中包裝對nock.cleanAllnock.restore的調用,但它沒有幫助。 我哪里錯了?

您正在為箭頭函數提供一個參數。 Mocha 認為你正在使用done ,你只需要讓它不使用參數。

(()=>nock.cleanAll())

代替:

(_=>nock.cleanAll())

因為您正在測試異步函數,所以需要通知 chai 被測試的函數是異步的。 這是一種通過在async函數之前添加async關鍵字來實現的方法;

 it('should succeed for correct nickname, move and gameID with game in progress', async () => Promise.resolve() .then(_ => { nock('http://localhost:8080') .post(`/api/user/${nickname}/game/${gameInProgress.id}`) .reply(200, { message: 'successful move' }) return logic.makeAGameMove(nickname, nickname2, {from: "e2", to: "e4", promotion: "q"}, gameInProgress.id, token) }) .then(res => { const {message} = res expect(message).to.equal('successful move') });

然后async before the fcallback functions

 afterEach(async _=> nock.cleanAll()) after(async _=> nock.restore())

暫無
暫無

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

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