Sanity Test for Landing Page

How to catch common page errors using a quick Cypress test.

If you browser the web the same way I do, you probably keep your browser DevTools console open. I often see errors even on the landing pages. Things like application reference errors and 404 for static resources not loading. In this blog post I will show how to quickly catch these errors via a safe sanity test. One could run these tests after every deploy to make sure the site works.

🎁 Find the source code and the tests in the repo bahmutov/cypress-sanity-test-example.

I grabbed an example static landing page from cruip.com via 40 Free HTML landing page templates. Then I have introduced two errors into the page: a JavaScript reference error, and a 404 by changing a line in public/index.html

1
2
- <script src="https://unpkg.com/[email protected]/dist/scrollreveal.min.js"></script>
+ <script src="https://unpkg.com/[email protected]/dist/scrollreveal.min.js"></script>

The landing page errors

Let's catch those errors by using tests.

Tests

You can find all tests in cypress/integration/spec.js file. To verify the failing tests, I run the tests using cypress-expect utility.

Catching errors

Cypress fails the test by default if it detects application errors or unhandled rejected promises, see docs.cypress.io. Just visiting the page will catch the reference error.

cypress/integration/spec.js
1
2
3
it('catches page exceptions', () => {
cy.visit('/')
})

Reference error fails the test

Ignoring errors

If you want to ignore an application error, define a listener

1
2
3
4
5
it('ignores all page errors', () => {
// https://on.cypress.io/catalog-of-events#Uncaught-Exceptions
cy.on('uncaught:exception', () => false)
cy.visit('/')
})

Ignoring app error

You can filter errors and only ignore certain ones.

1
2
3
4
5
6
7
it('ignores specific error', () => {
cy.on('uncaught:exception', (e) => {
// https://on.cypress.io/catalog-of-events#Uncaught-Exceptions
return !e.message.includes('ScrollReveal is not defined')
})
cy.visit('/')
})

Tip: watch filterig of application errors in this video Filtering app errors in Cypress tests.

Catching 404

Cypress can spy on network calls using cy.intercept command. We can see if any of the responses are 404. First, we can spy on the single problematic request.

1
2
3
4
5
it('detects a single 404', () => {
cy.intercept('**/scrollreveal.min.js').as('resource')
cy.visit('/')
cy.wait('@resource').its('response.statusCode').should('be.lt', 400)
})

The resource is not found

We can also confirm that every resource is successful

1
2
3
4
5
6
7
8
it('detects any 404', () => {
// https://on.cypress.io/intercept
cy.intercept('*', (req) =>
// assert the response
req.continue((res) => expect(res.statusCode, req.url).to.be.lt(400)),
)
cy.visit('/')
})

Checking every resource status code

Nice! We can quickly run the above tests against the deployed environment to make sure our users do not suffer from these mistakes.