hubot-typescript-boilerplate icon indicating copy to clipboard operation
hubot-typescript-boilerplate copied to clipboard

How test if my function throw correctly error

Open tibs245 opened this issue 6 years ago • 3 comments

Hi,

To begin : Thank you @JCMais for your boilerplate.

I will like test in my unit test when user say bad link, throw correctly error. But when my function throw error, my unit test fail. How I can catch this error for test it ?

Exemple : If axios catch error on @hubot http://myfakelink.fake

Have you a Idea ?

Thank you in advance

tibs245 avatar Jan 31 '19 08:01 tibs245

Hi @tibs245, you are welcome!

I'm afraid there is no good way to do that like you want, to make sure the link is correct you would be required to make a real request, this would make you test network dependent. And checking if the link is correct or not you would be testing axios handling of invalid domains, not really your code.

What I recommend is to create another test scenario, mocking axios to answer with an error instead of a success, and check if hubot answers with the messages you expect it to, for instance you would duplicate this it: https://github.com/JCMais/hubot-typescript-boilerplate/blob/master/src/scripts/tests/example.spec.ts#L17-L34

And change the mock to return an error, you can do that by using mockError instead of mockResponse, see: https://github.com/knee-cola/jest-mock-axios#axiosmockerrorerr-requestinfo

JCMais avatar Jan 31 '19 15:01 JCMais

Yes that I have done ! But my question is after. I want really that the error is intercepted by your error handler (Or other function catch). Or after my "mockError", the test fail automatically. I can't check if the hubot respond correctly

Concretly my code is : (I have not my code here, I simplify with my human memory)

try {
  await axios.get(url);
  res.say("ok2")
} catch (error) {
  res.say("Oh ! A Error ! I report it to admin !");
  throw error;
}

tibs245 avatar Jan 31 '19 16:01 tibs245

you should not be throwing errors inside your script like that, since this is basically an input error. Just test if the messages the bot sent match "Oh ! A Error ! I report it to admin !".

I've not checked on how to test errors like that, since that basically means testing the error handler here https://github.com/JCMais/hubot-typescript-boilerplate/blob/master/src/scripts/%232-error-handler.ts

JCMais avatar Jan 31 '19 16:01 JCMais