Current section: Test Structure 6 exercises

Handle Test Side Effects


00:00 So we have our code, and we have our tasks, and everything works just nicely. Until one day, Peter, the project manager, comes in and suggests an improvement. How about we add a weekday to the greeting message? So it would say, "Hello John, happy Monday!" That sounds like a fantastic idea, so we jump ahead and implement it. We create a new date, and we convert it to a local string,

00:19 using the locale of our application to be consistent, and grabbing the weekday in a long format, so it would say "Monday", "Tuesday", and so forth. And then we add it to the message, so now it says, "Hello name, happy weekday!" Because our intention behind this greet function has changed, we need to go to the tests and adjust the expectations here too.

00:37 In fact, this is the only legitimate reason to do so, because now our greet function does something it didn't do before, includes the weekday. So we adjust the expected string to be "Hello John, happy Monday!" Here's the problem with this test, though. It will only pass on Mondays. But this isn't what we want. We want reliable tests that pass whenever we call them.

00:56 So in this exercise, your task would be to handle the side effect introduced by the greet function. The side effect in the form of a new date constructor. You will mock that constructor, and make it return a fixed date, no matter when the test is run. And you will do so by introducing a setup phase to our test, to our little testing framework,

01:14 and add a new helper function called "beforeAll" and "afterAll" to orchestrate this mocking, and also clear up once the tests are done. That sounds like a fun challenge to me and I can't wait to see how you solve it.