我在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
的调用,但它没有帮助。你能帮我理解我哪里错了吗?谢谢你的帮助!
您正在为箭头函数提供参数。 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())