Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 使用Chai.throw异步捕获复杂Mongoose错误_Node.js_Mongoose_Mocha.js_Tdd_Chai - Fatal编程技术网

Node.js 使用Chai.throw异步捕获复杂Mongoose错误

Node.js 使用Chai.throw异步捕获复杂Mongoose错误,node.js,mongoose,mocha.js,tdd,chai,Node.js,Mongoose,Mocha.js,Tdd,Chai,Chai.throw用于针对其消息prop测试简单错误。在简单的错误情况下,这可以正常工作 it.only('Should catch a thrown message', () => { function throwSomething() { throw new Error('something') } expect(throwSomething).to.throw('something') }) 然而,在针对失败的Mongoose验证进行异步测试

Chai.throw
用于针对其
消息
prop测试简单错误。在简单的错误情况下,这可以正常工作

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

    expect(throwSomething).to.throw('something')
})
然而,在针对失败的Mongoose验证进行异步测试时,我发现我无法访问嵌套的错误消息。我最初希望使用带有try+catch的异步测试,但是catch块中的
expect
调用不能保证运行,在这种情况下,当测试实际上没有出错时,测试可能会通过

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回调,并在
.catch()
回调中调用
done()
,而不是异步测试我的模型。但是,如果我正在测试许多嵌套的Promise操作,我发现这种方法是不可取的

有没有办法使用
Chai.throw
捕获猫鼬产生的复杂嵌套错误