Moock Chai与Nock:为什么在“ after()”和“ afterEach()”中进行清理时会出现超时错误?

时间:2018-09-08 19:05:23

标签: javascript node.js mocha nock

我在Mocha / chai套件中对Nock进行了获取请求(模拟?),它似乎工作正常。但是当我要清理并在describe之后将一切恢复正常时,我会遇到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的调用,但这没有帮助。您能帮我了解我要去哪里了吗?感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

您正在为箭头函数提供参数。 Mocha认为您正在使用done,您只需要进行设置即可,因此不使用任何参数。

(()=>nock.cleanAll())

代替:

(_=>nock.cleanAll())

答案 1 :(得分: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())