Loading
Current section: Globals 5 exercises
solution

Global values

Loading solution

Transcript

00:00 To mock a global location object in test, I will start from the test setup. First, I will add the before all hook, and in that hook, I will call v stub global. This method accepts two arguments. The first one is the property name that you want to mock. So in this case, it's a location string. And the second one is the value,

00:19 the mock value for this property. I will use this URL instance as the value. This way, the global location object will share the URL properties they have in common, like host name, port, and href. Effectively, the reason for this call signature is very similar to the one behind v.spy on. What vTest is going to do, it will reassign the global property

00:39 to the next value. So basically, property being location, and value being this new URL. And since I'm introducing this mock over here, I will make sure to clean up after myself in the after all hook by calling v unstub all globals. So what this is going to do is revert any changes

00:57 we introduce here, and basically give us back the proper unmodified location object after these tests are done. With this setup in place, I can finally start testing all the different behaviors of this toAbsoluteURL function. So the first one is where I expect it to be called with the

01:13 absolute URL and return that absolute URL as is. That is pretty simple. The second test case has to do with path names. So in the first scenario, I call toAbsoluteURL with a path name that is relative to the root. So in this case, I expect HTTP localhost resource be printed. Notice that

01:32 this one doesn't have the base path from here, because this path name is relative to the root, which is HTTP localhost. And the second scenario, I expect toAbsoluteURL when it's called with a path name relative to the current path to return it including the base. So in this case, I will

01:50 have base slash resource. With this setup, I will try running a test with npm test to see them passing. So basically what we did here, we introduced the test setup. In the before all hook, we called v.stopGlobal that stops the global location property, this global location object, to have

02:08 the value of this new URL instance. Then we clean after ourselves with v.unstopAllGlobals. So we're doing this to achieve proper encapsulation for this test. So no matter the testing framework setup or the test environment, we know that these URLs will be always consistent, so we're able to reliably assert on them in tests.