Verify that an exception is thrown using Mocha / Chai and async/await

后端 未结 11 886
花落未央
花落未央 2020-12-14 05:50

I\'m struggling to work out the best way to verify that a promise is rejected in a Mocha test while using async/await.

Here\'s an example that works, but I dislike t

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-14 06:39

    I use a custom function like this:

    const expectThrowsAsync = async (method, errorMessage) => {
      let error = null
      try {
        await method()
      }
      catch (err) {
        error = err
      }
      expect(error).to.be.an('Error')
      if (errorMessage) {
        expect(error.message).to.equal(errorMessage)
      }
    }
    

    and then, for a regular async function like:

    const login = async (username, password) => {
      if (!username || !password) {
        throw new Error("Invalid username or password")
      }
      //await service.login(username, password)
    }
    

    I write the tests like this:

    describe('login tests', () => {
      it('should throw validation error when not providing username or passsword', async () => {
    
        await expectThrowsAsync(() => login())
        await expectThrowsAsync(() => login(), "Invalid username or password")
        await expectThrowsAsync(() => login("username"))
        await expectThrowsAsync(() => login("username"), "Invalid username or password")
        await expectThrowsAsync(() => login(null, "password"))
        await expectThrowsAsync(() => login(null, "password"), "Invalid username or password")
    
        //login("username","password") will not throw an exception, so expectation will fail
        //await expectThrowsAsync(() => login("username", "password"))
      })
    })
    

提交回复
热议问题