I’m trying to write a test case for a debugging method that writes messages to the JavaScript console using console.log(). The test has to check that the message has been successfully written to the console. I’m using jQuery.
Is there a way to attach a hook to console.log() or otherwise check that a message has been written to the console, or any other suggestions on how to write the test case?
console.logdoesn’t keep a record of messages that are logged, or emit any events that you could listen for. It’s not possible for your tests to directly verify its output from JavaScript. Instead, your test code will need to replaceconsole.logwith a mock implementation that does keep track of log messages for later verification.Mocking is a common feature supported by most JavaScript test frameworks. For example, the Jest test framework provides a
jest.spyOnfunction which replaces a given method with a mock implementation that records the arguments for each call in a.mockproperty before passing them on to the original implementation. After each test you may want to calljest.clearAllMocks()to reset the recorded argument lists for the next test, or use the equivalentclearMocks: trueconfig option.If you’re not using a test framework (you probably should), you can create a simple mock yourself.