Loading
Current section: Globals 5 exercises
solution

Global methods

Loading solution

Transcript

00:00 To test that the print server URL is actually printing something to the console, I would have to spy on the console.log method. To do that, I would go to the B4ALL hook and call v.spyOn. This is the same utility that you've used to spy on your own classes and their methods previously. As a target, I will provide a global console object.

00:19 It is the method name, the log method, the one I want to spy on. What this is going to do, it will introduce the mock, it will patch console.log, and VTest will start recording any calls to this method during the tests. Next, in the afterEach hook, I will call v.resetAllMocks. This utility will do two things.

00:38 First, it will throw away any recorded calls between the tests so they don't persist. And second, it will also throw away any mocked implementations that we might have added in individual tests. And lastly, in the afterAll hook, I will call v.restoreAllMocks. And this one is a little different. It will basically restore any mocks that we introduced before,

00:58 effectively unpatching, unmodifying the console.log method so it behaves as usual. With this spy in place, I can finally start to certain on the console. So, in this first test, we're printing the URL for a server that only has a host. So, I expect the console.log to be called with the respective message.

01:15 The server is listening and providing the address and a trailing slash. Now, in the second scenario, we also include an optional port. So, let me reflect that in the URL, 5639. Now, if I run tests, I will see them passing, but I will also see that this message is being printed in the console during the test run.

01:36 And sometimes this is not what you want because it may clutter the test output. Here's what you can do about it. In the beforeAll hook, you can mock the implementation for the console, providing an empty function as the implementation. This will effectively force console.log to do nothing in tests. But be mindful here because once you mock this implementation,

01:55 you can no longer use resetAllMocks because this utility will throw away this mock after the first test. Instead, you should use clearAllMocks. This is a similar utility. It will clear any recorded calls, but it will preserve any mock implementations that you introduce in the test setup. So, with this one, we can see the test passing

02:15 and no console logs actually being printed in the test output.