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