繁体   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