Imagine you are using all the modern ES6 methods in your application. Most modern evergreen browsers support everything, right? But once in a while you see in your crash reporting system errors like "X.findLast is not a function". Ughh, what is going on? Why is this ES6 Array method missing? And most importantly, how do we test to prevent this?
The application
Let's take an application that uses Array.findLast
method. The page has a button and once the user clicks on it, it finds the last element in the array that satisfies a predicate function.
1 | <body> |
🎁 You can find the source code for this application and for the tests used in this blog post in the repo bahmutov/cypress-polyfill-example.
The spec
We can write a test for this app using Cypress. Click on the button, check the output.
1 | it('finds the last element', () => { |
The simulated browser without findLast method
How do we test our application in an older browser that does not support ES6 Array methods? It is hard (and unsafe) to keep a local old browser installed on your machine; most browsers try to update themselves. You could use a Docker image with an older browser installed, but that is a pain. Instead, we can do the following trick: simulate an older browser by deleting the ES6 methods. Cypress cy.visit command allows us to access the application window
object before the application loads. We can "adjust" the Array.prototype
methods and see if the application still works.
1 | it('finds the last element (older browser)', () => { |
Now we are talking!
The polyfill
We need to support browsers that do not have the methods the application code uses. The best way is to use a polyfill. For example, we could include the core-js from CDN.
1 | <body> |
Let's run the test now. Beautiful, it works. The core-js-bundle
JavaScript "fills" the Array.prototype.findLast
method we have deleted, and our application is happy again.
Confirm the polyfill loads
Because we are great at Cypress Network Testing and every day study a free lesson during Cypress Training Advent Calendar 2022, we can spy on the core-js
library and confirm it loads correctly.
1 | it('finds the last element (older browser, observe polyfill loads)', () => { |
Tip: the browser caches the polyfill, so to see it load 100% of times, you need to strip the caching headers.
Strategy
I don't think you need to recreate every possible older browser environment and run every test. A single test that specifically checks that the polyfill is loaded and applied would be enough. You can add more regression tests as needed if you find a bug.