简体   繁体   中英

How to validate thrown javascript exception using chai and mocha?

I have MongoDB Query function which in which query params are validated Here is the function Note: user is mongoose model

function fetchData(uName)
{
    try{
        if(isParamValid(uName))
        {
            return user.find({"uName":uName}).exec()
        }
        else {
            throw "Invalid params"
        }
    }
    catch(e)
    {
        throw e
    }
}

To test this with invalid username values, I have written test code for that using mocha, chai, and chai-as-promised for promise-based functions

describe('Test function with invalid values', async ()=>{
    it('should catch exception', async () => {
        await expect(fetchData(inValidUserName)).to.throw()
    })

    it('should catch exception', async () => {
        await expect(fetchData(inValidUserName)).to.throw(Error)
    })

    it('should catch exception', async () => {
        await expect(fetchData(inValidUserName)).to.be.rejectedWith(Error)
    })

    it('should catch exception', async () => {
        await expect(fetchData(inValidUserName)).to.be.rejected
    })
})

None of them pass the test, How do I write a test case to handle exception for invalid userName values

You are passing the result of fetchData function call to expect function. Instead of calling the fetchData function inside expect function, pass a function to expect function.

it('should catch exception', async () => {
    await expect(() => fetchData(inValidUserName)).to.throw('Invalid params')
})

Use try/catch

it('should catch exception', async () => {
    try {
      await fetchData(inValidUserName);
    } catch(error) {
      expect(error).to.exist;
    }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM