happo / happo-cypress

A Happo integration with Cypress.io
35 stars 4 forks source link

Resolve styles from right baseUrl in SPA #67

Closed trotzig closed 3 years ago

trotzig commented 3 years ago

In a single-page-application, the document you land on will dynamically change its location with history.pushState. This leads to a problem when downloading relative assets, if the original document is in a different sub path than the tests. Take this example:

Start page is loaded at url "/". Link "admin" is clicked. Page "/admin/start" is loaded. A happo screenshot is taken.

If any css was added in the initial page load, and it has a relative path (e.g. "styles.css", or "./styles.css"), the screenshot will be missing those styles. To fix this, we need to "remember" the baseUrl for style elements (including ). We do this by subscribing to the "window:load" event from Cypress and setting the baseUrl as a property on all css elements found right at the start.

This isn't a fool-proof solution. There can still be cases where the style element isn't present on initial page load, but is added dynamically on the start page after it has been loaded. Then, the baseUrl property wouldn't be set and Happo would look for the css file relative to e.g. /admin/. I can live with this however as I think the current fix will cover 99% of all cases. Plus, using relative urls to style sheets isn't too common.