首页 > 解决方案 > 尝试在 Mongoose 预保存挂钩中测试休息调用时出错

问题描述

我的测试有问题,因为在 Mongoose 的预保存挂钩中,我调用了一个休息服务来根据模型数据设置一个令牌。

我正在尝试使用 nock 使其余调用模拟,但没有任何反应,测试仍然出现此错误:

Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves

这是预保存中的代码:

  if (this.token_id !== undefined) {
    const {data: {token}} = await updateToken(
      this.token_id,
      {this.username, this.password}
    )
    this.token_id = token
    this.username = null
    this.password = null
  } else {
    const {data: {token}} = await createToken(
      {this.username, this.password}
    )
    this.token_id = token
    this.username = null
    this.password = null
  }

这里 updateToken 和 createToken 返回 axios 调用(分别是 put 和 post) 在测试中我有类似的东西:

before(done => {
nock('http://localhost:3000/tokens')
      .post('/credentials', data)
      .reply(200, { token: 'sometoken' })
})

it('Should save all the data with the token', async() => {
      await Model.create(ModelFactory.build({
        _id: someId
      }))
}) 

也许我做错了什么?

标签: javascriptnode.jsmongoose

解决方案


该错误已经说明了问题所在。如果有done,则需要调用它。在里面donebefore它没有被调用。由于它不是异步的,因此不需要done. 它应该是:

before(() => {
    nock('http://localhost:3000/tokens')
      .post('/credentials', data)
      .reply(200, { token: 'sometoken' })
})

推荐阅读