Hey folks So I have had a couple of in situations when I was writing some tests where I had some code that would give me some sort of warning maybe it's using the invariant module or I'm just doing a console.air or consultant more or something like that. Or maybe I'm rendering a React component that will throw an error or something like that and I want to write a test to make sure that that error is thrown or whatever.
So in in these sorts of scenarios, you're going to get console.errors getting logged. And so, I just wanted to talk about how I do that. So what I do,Is I am I do just that spy on console error and do that in a before each and then inside the test itself.
I will define what I want it to be mocked as and I don't want to have my tests muddied up by all the console output from my source. So whether that's console.org, or error or log or anything, I want my test to be totally free of all of those things.
And so if I'm expecting to have some logs of some kind as I'm running my tests, I'm going to need to mock all of those things. So that I don't have aBunch of noise in my test output And so typically console.ir is going to be mocked and I'll say mock implementation empty arrow function, so it doesn't actually log anything.
But sometimes this can be a problem because sometimes let's say that you are expecting to get an error but you're not going to be getting the like the error that you get when you first write it actually you get a different error for a different reason later and if you don't assert on the error that you actually got then you'll be in a bit of a bind and so you when you mock the implementation like that, you want to make.
Sure that you are asserting that yes, this was called and we know what it was called with. So you want to insert what it's called with?The other side of this is let's say that you want to make sure that an error is not called because you're handling a situation where maybe react with typically error like for example when you unmounted component and a request finishes you want to make sure that there's no error about setting state on an unmounted component, for example.
And so in that case, what I did just today was I set my error at or I I did spy on my error, but I did not want it to want to mock the implementation. I want to keep the original implementation.And then, I perform all my actions, whatever NI assert that the console error was not called.
In this case, you do not want to unlock the implementation because if you do have an error you want to be able to see what that error was. So anyway, I thought that might be interesting. And in yeah, if you ever run into situations where you have a bunch of errors or logs or anything, just make sure you clean those up.
So, they're not distracting from the output of the test. Hope that's interesting. Have a wonderful day.