Deep diving PageObject pattern and using it with Cypress

If you’re reading this, you’re probably not having fun writing tests anymore.

PageObject became known on Selenium’s era, but today I’ll show you how to use this amazing pattern with Cypress.

What is it

PageObject is a design pattern that helps you to enhance test maintenance and reduce code duplication. In addition, it’s a better way to describe and document the interface operation flow of your application.

According to Martin Fowler, a page object should allow a software client to do anything and see anything that a human can. Also, these objects shouldn’t usually be built for each page, but rather for the significant elements on a page.

Using it

Basically, a page object should provide an interface that’s easy to program, encapsulating all the methods that find and/or manipulate the application elements.

Suppose we have an e-commerce, we could have a HomePage class that contains a link to the SignInPage, for example:

Usually, page object operations should return fundamental types (strings, numbers, etc). However, it’s important to point out that we can also return another page object (that’s a good practice if we’re navigating to another page).

Talk is cheap, show me the code

In the last month I had some free time to compare some javascript frameworks to automate E2E web testing. I must admit, I have just fallen in love with Cypress. ❤

Cypress has an easy API, and I’ll use it to show you how to apply the PageObject pattern in a simple sign in flow. The purpose of this article isn’t to go deeper into Cypress configs and docs, so you can check it here.

So, how does our test look like?

And which page objects were created?

A bit more about Cypress

Talking about tests is usually painful for some people. So, I want to share my experience about how simple was to use Cypress.

Cypress is a complete E2E testing experience, providing a test runner and a dashboard service. For now, we decided to use only the test runner on a CircleCI container. Basically, we’ll run the test suite every time that a pull request is opened.

We could do that in less than a day, and you can check an example here.

The bottom line is, you can use this pattern with many others libraries in many other ways. The given example was used only to demonstrate how simple and readable your tests can be.

I hope you enjoy it, thanks for your time!

References

https://martinfowler.com/bliki/PageObject.html