首页 > 解决方案 > 使用 Chai.throw 异步捕获复杂的 Mongoose 错误

问题描述

Chai.throw用于针对他们的message道具测试简单的错误。在简单的错误情况下,这可以正常工作。

it.only('Should catch a thrown message', () => {
    function throwSomething() {
      throw new Error('something')
    }

    expect(throwSomething).to.throw('something')
})

但是,在针对失败的 Mongoose 验证进行异步测试时,我发现我无法访问嵌套的错误消息。我原本想用 try+catch 来使用异步测试,但是expectcatch 块内的调用不能保证运行,在这种情况下,当测试实际上没有出错时,测试可能会通过。

it.only('Errors on save if username is not unique', async () => {
    // setup original user
    const original = new UserModel(testParams)
    await original.save()

    try {

      // try to create a new user with the same username
      const duplicate = new UserModel({
        username: testParams.username,
        email: 'test_other@mail.com',
        password: testParams.password
      })

      // save the user that has a non-unique username
      await duplicate.save()
    } catch (err) {

      // confirm the nested error was as expected
      expect(err.errors.username.message).to.equal(
        'Error, expected `username` to be unique. Value: ' +
        '`' + testParams.username + '`'
      )
    }
})

如果我要调用expect(duplicate.save).to.throw('...')它,它不会检查我想要的错误字段。

另一种选择是,我不是异步测试我的模型,而是使用 Promise 回调,并在回调done()内部.catch()调用。但是,如果我正在测试许多嵌套的 Promise 操作,我发现这种方法是不可取的。

有没有办法用来Chai.throw捕获 Mongoose 产生的复杂嵌套错误?

标签: node.jsmongoosemocha.jstddchai

解决方案


推荐阅读