Skip to content

Use window.location.assign instead of href

Savas Vedova requested to merge use-window-location-assign into master

What does this MR do and why?

Changes the implementation of visitUrl. Instead of using location.href, let's use location.assign.

While both location.assign and location.href can be used to achieve the same result, location.assign is easier to test for the following reasons:

It's possible to spy on the implementation and check the parameters passed

const mySpy = jest.spyOn(window.location, "assign")

// call functions to be tested...

expect(mySpy).toHaveBeenCalledWith("example.org")

It's easier to capture bugs

With spies, we can test how many times the function has been called therefore we can catch unwanted calls:

// Imagine the code assigns `href` twice. In reality, the user will be redirected to `url-1`.
window.location.href = "url-1"
window.location.href = "url-2"

// But the following expectation will still be true and won't capture `url-1`. 
expect(window.location.href).toBe("url-2")

// If we were using `location.assign` we could also test something like:
expect(window.location.assign).toHaveBeenCalledTimes(1)
expect(window.location.assign).toHaveBeenCalledWith("url-2")

Screenshots or screen recordings

No visual changes.

How to set up and validate locally

  1. Checkout this branch
  2. Run yarn jest to run all tests locally

MR acceptance checklist

This checklist encourages us to confirm any changes have been analyzed to reduce risks in quality, performance, reliability, security, and maintainability.

Edited by Savas Vedova

Merge request reports

Loading