Global values
Loading "Global Values"
Run locally for transcripts
vi.spyOn()
is a great way to mock and control global methods. However, when your code depends on global values, you need to employ a different approach.In this exercise, we are testing the
toAbsoluteUrl()
function that looks like this:/**
* Returns absolute URL from the given URL.
*/
export function toAbsoluteUrl(url: string): string {
return new URL(url, location.href).href
}
This is a browser-only function whose purpose is to ensure the
url
we provided to it is returned as an absolute URL. If the url
is absolute already, it's returned as-is. But if it is a relative URL (i.e. a pathname), it must be resolved against the current location.href
.Because of the dependency on
location
, we will be testing the toAbsoluteUrl()
function in the happy-dom
environment, which polyfills the global location
object.import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'happy-dom',
},
})
By default,
location.href
in HappyDOM is set to http://localhost:3000/
. However, for our new test to comply with the Golden Rule of Assertions, the value of the location.href
must be set on the test's level. Otherwise, a change in Vitest configuration could result in different absolute URLs being produced, thus failing the test prematurely.Moreover, bringing the actual
location.href
value to the test level will give us more control over different URL-related scenarios (e.g. IPv4 vs IPv6 URLs).For that, we are going to use the
vi.stubGlobal()
utility.๐จโ๐ผ In this exercise, use the
vi.stubGlobal
API to mock the value of the global location
object in the test suite. Verify your solution by running npm test
.๐ฆ Note thatlocation
inherits fromURL
, which means it can be partially mocked by using aURL
instance as its value.