【问题标题】:Mocha Chai with Nock: why am I getting timeout errors when doing cleanup in 'after()' and 'afterEach()'?Mocha Chai with Nock:为什么在“after()”和“afterEach()”中进行清理时会出现超时错误?
【发布时间】:2018-09-08 19:05:22
【问题描述】:

我在 mocha/chai 套件中使用 Nock 存根(模拟?)获取请求,它似乎工作正常。但是当我想在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.cleanAll 和 nock.restore 的调用,但没有帮助。我哪里错了?

【问题讨论】:

    标签: javascript node.js mocha.js nock


    【解决方案1】:

    您正在为箭头函数提供参数。 Mocha 认为你在使用done,你只需要让它不使用任何参数。

    (()=>nock.cleanAll())
    

    代替:

    (_=>nock.cleanAll())
    

    【讨论】:

      【解决方案2】:

      因为您正在测试异步函数,所以需要通知 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())

      【讨论】:

      • 谢谢——我尝试了你的解决方案,但它似乎对我不起作用......正如我所说,我试图将 after 和 afterEach 包装在 Promise 中,但它也没有工作。顺便说一句,为什么after 和afterEach 需要异步? nock.restore 和 nock.cleanAll 是异步的吗?
      猜你喜欢
      • 2018-04-27
      • 1970-01-01
      • 2018-11-27
      • 2022-11-25
      • 2022-06-15
      • 2012-05-19
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      相关资源
      最近更新 更多