⚠️ This lesson is retired and might contain outdated information.

Use protractor to catch errors in the console

Share this video with your friends

Social Share Links

Send Tweet
Published 10 years ago
Updated 4 years ago

Protractor gives you access to the console log while it is testing. This functionality could be used to verify that no errors are occurring, or other similar things you might want to test.

[00:00] It sounds obvious, but Protractor can only test the things you tell it to. What that means is that it can actually miss certain things if you don't tell it to look out for them. You can see here that we have our very basic Protractor test. If we run our test, it passes. Everything is fine.

[00:17] If we go in and make a change to our code here so this code runs when the button gets clicked...Maybe we want to track an analytics event when that happens as well, so we're going to call analytics.track.

[00:31] We'll refresh our app here, live. When we do that, we can see that we get an error. That error is, of course, because the analytics object is not defined. We didn't remember to initialize that in our code.

[00:46] If we go run our tests here, you can see that our tests still pass even though our application has an obvious error and something that could be a big deal in a production scenario. The way that we can catch errors like that is by adding an afterEach hook.

[01:02] Within this afterEach callback, we're going to call this browser.manage().logs() function to get the logs, get the browser logs out of there. In our callback, we'll actually get that browser log object back, or the array. We can then check to verify that the length is zero, meaning that there have been zero errors.

[01:28] If we then run our tests again, we'll see that they do actually fail. Our error message here is that we "Expected 1 to equal 0We expected that browser log to be empty, but it's not.

[01:41] What we can do here, if we want to actually see what that error is, which...Not necessarily that you would debug it this way, but if you want to see what that error is, you can get that array and just pass it to the JSON stringify method so that you can actually see the contents of those errors.

[01:58] We can see here that we do get a whole big...We get the entire stack trace in our console here. We can see that "analytics is not defined" message up there is the root cause.

[02:10] Lastly, if we go back to our application and remove the problematic code, save that file, and then run our tests again, we'll see that it does pass as expected because we've gotten rid of our console errors.