0

I'm trying to write integration tests with Mocha and Chai but Chai doesn't seem to catch the errors.

Code being tested:

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()
}

And the test code :

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()
})

I expect the test to pass, but the code I have fails with the following error message:

  AssertionError: expected [Function] to throw an error
Lawand
  • 35
  • 1
  • 7

1 Answers1

2

The problem is to.throw() expects a function but using async, you return a Promise.

So you have tu use .to.be.rejected instead of to.throw().

You need chai-as-promised and you can try something like this:

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

Don't use async/await into expect because chai will handle it.

Also, you can check this question

J.F.
  • 13,927
  • 9
  • 27
  • 65