This blog post shows another example automation use case in Cypress Test Runner via its Chrome Debugger Protocol connection. Let's take a page that uses a custom fancy font from Google Fonts site to render the body text. You can find this example page in the repo bahmutov/fastify-example.
1 | <html> |
How does the page look while the font is loading? Using the cy.intercept command we can slow down loading either the initial CSS resource, or the actual font (see the bonus lesson in my Cypress network testing course to learn how to slow down network calls). While the font "Satisfy" is loading, the browser shows the fallback font family "cursive" which loads the system font from my laptop.
How do we confirm the font "Satisfy" really loads? If we ask the browser what the font should be used, it will answer "Satisfy" right away. The DOM simply returns what we listed in the element's styles. Let's write a test that uses the Chai-jQuery assertion "have.css"
1 | it('shows the font listed in the style', () => { |
Hmm, the .should('have.css', 'font-family')
assertion yields the "Satisfy, cursive" style string, not the actual rendered font name. You can see how the test passes, even if the laptop has its network WiFi turned off.
The font "Satisfy" does not even load, yet the test only looks at the listed style. How do we get the actual rendered font name?
Rendered font in DevTools
If you inspect the element in the Chrome DevTools, you can find the "rendered font" name after the font successfully loads and is applied to the element. The system font name is available in the DevTools Elements Tab at the bottom of the "Computed" properties sub tab.
Let's get this rendered font name from the test. It takes a few calls via Cypress.automation
low-level command which uses the existing Cypress Automation Chrome Debugger Protocol connection to send CDP commands.
1 | // Cypress.automation returns a Promise |
I will use my cypress-cdp plugin to get the element's Node ID we need to fetch the rendered fonts using CDP command.
1 | $ npm i -D cypress-cdp |
From the spec file I import the plugin and use a Chrome-based browser to run the test. We need to get the rendered font, which we can do using the Chrome Debugger Protocol command CSS.getPlatformFontsForNode
1 | import 'cypress-cdp' |
The test retries fetching the rendered font until the real font "Satisfy" loads and is used by the browser to render the text in the <body>
element.
Nice!