【问题标题】:How to use expect.to.throw with Mocha and Chai?如何在 Mocha 和 Chai 中使用 expect.to.throw?
【发布时间】:2021-02-14 08:53:30
【问题描述】:

我正在尝试使用 Mocha 和 Chai 编写集成测试,但 Chai 似乎没有发现错误。

正在测试的代码:

export async function createUser(
  username: string,
  password: string,
): Promise < {} > {
  const user = await User.findOne({
    username
  })
  if (user) {
    throw new UserInputError('Username is taken', {
      errors: {
        username: 'Username is taken',
      },
    })
  }

  if (username.trim() === '' || null) {
    throw new UserInputError('Must not be empty', {
      errors: {
        username: 'Must not be empty',
      },
    })
  }

  const hash = crypto.createHash('sha512').update(password).digest('hex')

  const newUser = new User({
    username,
    password: hash,
  })

  return newUser.save()
}

还有测试代码:

it('Fails when no username is provided', () => {
  const password = uuid()

  expect(async() => {
    await client.mutate({
      mutation: gql `
              mutation($username: String!, $password: String!){
                createUser(username: $username, password: $password) {
                  id
                  username
                }
              }
            `,
      variables: {
        username: '',
        password,
      },
    })
  }).to.throw()
})

我希望测试通过,但我的代码失败并显示以下错误消息:

  AssertionError: expected [Function] to throw an error

【问题讨论】:

    标签: typescript mocha.js chai


    【解决方案1】:

    问题是to.throw() 需要一个函数,但使用async,你返回一个Promise

    所以你必须使用.to.be.rejected 而不是to.throw()

    你需要chai-as-promised,你可以试试这样的:

    it('Fails when no username is provided', () => {
        expect(client.mutate({...})).to.be.rejected;
    });
    

    不要在expect 中使用async/await,因为chai 会处理它。

    另外,您可以查看question

    【讨论】:

    • 啊,谢谢 .. 这解释了为什么它没有按预期工作。
    猜你喜欢
    • 2014-03-02
    • 1970-01-01
    • 2017-06-05
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2019-07-18
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多