Speeding up Cypress Automation Tests

Speeding up Cypress Automation Tests

Here are a few tips on making your Cypress automation tests runs faster.

NOTE: Some of these may seem trivial but they are all actual mistakes made by me. I hope you’ll learn from my mistakes.

Write one big test rather than several small ones

A real-world integration test typically involves signon, etc before testing the actual functionality. Each test you add will therefore add to the time taken. Also, as Cypress’s best practices document explains, Cypress does some housekeeping between each test. This will also slow you down if there are too many small tests.

Use before & beforeEach judiciously.

Consider this example:

1
2
3
4
5
	beforeEach(()=>{
		cy.login();
		cy.get('[.homePage]').should('be.visible');
	});
	//10 tests

Here, the test will login 10 times - once before each test. What I actually wanted was to login once and so should replace beforeEach with before

1
2
3
4
5
	before(()=>{
		cy.login();
		cy.get('[.homePage]').should('be.visible');
	});
	//10 tests

Avoid waiting for arbitrary periods of time.

Cypress explains that cy.wait(Number) is an anti-pattern and you can almost always replace it with an assertion. Read Cypress’s detailed explanation and examples to understand more. If you succumb to the temptation to add cy.wait() anyway, they will eventually become a time-sink.

Tweak Cypress’s configuration to remove unnecessary disk I/O

Cypress aims to “just work” and does this admirably. A configuration file is automatically created by Cypress on the first run. Some of the options here increase the disk I/O and hence slow down Cypress itself. The main culprits are:

Turn these off or turn on only for nightly runs etc. where you are not worried about the time taken.

Tag tests and run only the ones you need to

Cypress’s list of curated plugins includes cyress-grep. Using this plugin, you can run tests by grepping their titles or custom tags you’ve added to each test. Use this ability to run only the necessary smoke or feature-specific tests.

Incorporate Cypress into your CI/CD

This one is a little harder to implement but worth the effort. Take the time to read and understand how Cypress can be plugged into your CI/CD pipeline. As with everything else, Cypress’s documentation here is extensive. As your test suite grows, offloading running the suite to some other system may be more performant than running all the tests locally on your laptop.

This article is also posted on dev.to

comments powered by Disqus