Loading
Current section: Functions 5 exercises
solution

Spies

Loading solution

Transcript

00:00 In the user service test, I have this logger instance that I'm going to provide to the user service right here. But before I do, it would be nice to spy on the logger.log method. Well, I can try doing logger.log equals v.fn, and this will largely work replacing this method

00:16 with a mock function. But the problem with this approach is that it will be throwing away everything the log does, and this may not be something you want in certain situations. So instead, I will use the v.spyown API. This API accepts two arguments. It's the target object,

00:32 in this case, it's the logger class, and the method name that you want to spy on. In this case, it's the log method. The reason for this unusual call signature is how the spy on function works. Effectively, it reassigns the method on the target by wrapping it in a spy. So in this case,

00:50 something like this. And in order for it to dynamically rewrite methods on objects, you would have to provide the method as a string. So in our case, it's the log string. Once I do this, I construct the user service and create the user as usual, and now I have to write some assertions

01:06 around the logger. So the first one would be asserting that the logger.log was called with the correct arguments. And notice how I'm asserting directly on the logger class. I don't have to reference any internal mock functions, nothing like that. It's already baked in by VTest by

01:22 calling v.spyown. So I'm going to expect that logger.log to have been called with two arguments. The first one will be the event name, create user, and the second, the right payload, in this case, the event ID or the user ID. And the second assertion is to make sure that the logger.log

01:39 was called just once, and I will use to have been called once to do just that. Now if I run the tests, I can see that the logger is functional right here. It prints the event in the console, but also I have an automated test that verifies that. You may be wondering, well,

01:55 isn't testing logger in this case an implementation detail testing? And otherwise, you would be right. But imagine if this user service class is something you develop as a part of some SDK for other developers to consume. So suddenly, logger printing something in the console becomes

02:11 the part of your public promise. So you have to test that intention, and it's a viable intention to test. And now you know how to do that using the v.spyown API.