Mocha Chai和Nock:为什么我在'after()'和'afterEach()'中进行清理时会出现超时错误?

问题描述 投票:0回答:2

我在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.cleanAllnock.restore的调用,但它没有帮助。你能帮我理解我哪里错了吗?谢谢你的帮助!

javascript node.js mocha nock
2个回答
1
投票

您正在为箭头函数提供参数。 Mocha认为你正在使用done,你只需要这样做就不会使用任何参数。

(()=>nock.cleanAll())

代替:

(_=>nock.cleanAll())

0
投票

因为您正在测试异步函数,所以需要通知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())
© www.soinside.com 2019 - 2024. All rights reserved.