Debug Browser Javascript Tests
Explore methods to debug Jasmine tests running in browser environments. Learn to capture console logs with custom reporters, use browser developer tools for live debugging, set breakpoints, and understand asynchronous log behaviors to improve your JavaScript testing process.
Using ‘console.log’
At the time of writing of this course, using jasmine-browser-runner runSpecs doesn’t output the instances of console.log to the terminal (the Node.js process) because the tests execute in the browser environment. We can see these logs in the browser’s console part of the developer tools. If that browser is headless, then there’s no chance to see the logs.
There is a way to set up a reporter for the jasmine-browser-runner so that the logs show on the terminal. It’s based on this Jasmine issue response.
See the spec/helpers/logs.js in the code playground below. It replaces the console.log function with a custom one by using spyOn. It stores the arguments of each console.log in an array logs, and afterEach spec stores the logs in the spec context for spec/support/reporter.js to use. Since the reporter runs in the context of the Node.js process, it can call console.log and result in the output showing on the terminal. That’s precisely what it does.
All this sounds pretty complicated, but rest assured, we cover another way later on in the lesson.
(function () {
let logs = [];
beforeAll(function () {
const originalLog = console.log;
spyOn(console, 'log').and.callFake(function () {
logs.push(arguments);
originalLog.call(console, arguments);
});
});
afterEach(function () {
setSpecProperty('consoleLogs', logs);
logs = [];
});
})();