Cypress – Writing Your First Test

Cypress – Writing Your First Test

Powerful JavaScript testing framework

So…it’s been a while, huh? The last post was months ago, I feel like I abandoned you. But these last few months have seen the arrival of my second child and a global pandemic that blurred the lines of personal and work life into one. Priorities and a lack of time have just meant I’ve not been able to sit down and write the amount of content, and at the quality that I’d like. I could have hashed out a few rushed articles, but then you potentially don’t learn what I’m trying to teach, and that’s not good.

With that said, I hope to get back to it now and get back to adding regular content. Starting with a new series and one I’m doing off the back of a fair bit of Cypress usage myself. Cypress is a hugely impressive testing tool, the vast majority of my 13 years experience has come from C# and Selenium, but recently, to move with the industry, I’ve tried to look at more popular JavaScript tools.

Cypress is one that I initially shunned because I prefer to work with libraries as opposed to frameworks. I like to have the freedom to build my own framework around the libraries that I pick and choose to solve the problem I’m working on. Cypress is a ready “out of the box” framework, which I’ve come to learn is just an awesome thing. It is so powerful from the moment you install and it is so quick and simple to get solid and robust tests written and running with a very shallow learning curve.

If you haven’t used Cypress before, then this series of articles intends to get you in a position that you’ll be comfortable setting up a Cypress install and writing tests. We’ll even build on that by using page objects, writing our own utility classes and writing custom commands to extend Cypress even further. In this first article, we’ll get you set up with a Cypress install in a new project, get it configured, and write our first test.

Before we begin, to follow along with this article, you should have Visual Studio Code installed and Node.Js installed (at the time of writing, 12.18.0 is the version to use, but if it’s updated since, just use the latest LTS version)

Assuming both of the above are installed, let’s begin.

  1. Create a new directory for your project, and with VSCode open, use the terminal (Ctrl+Shift+’) with the following command to change the active directory to your project directory

    cd your/project/path
  2. This isn’t a necessary step, but it’s always good practise to initialise your project directory with the basic files needed when working with npm packages.

    npm init

    This will ask you a series of questions in the terminal, but feel free to just keep mashing the enter key as it will use default values if you don’t feel like answering. Once this is done, you’ll have a package.json file in your project folder, which will contain any details you might have entered in the questions mentioned above, any custom scripts (we’ll get on to that later) and a list of packages, this will currently be empty. Let’s fix that
  3. Now it’s time to get Cypress downloaded. Cypress comes in the form of a package, which we’ll use npm to retrieve and install into our project. This step couldn’t be easier, and a simple command will do all the tricky work for you. The command you need to use is:

    npm install cypress --dev

    The command is pretty self-explanatory except for the last part. The –dev flag tells Cypress to install as a dev dependency, which means it is only required for the development. Installing without that flag tells our project to install it as a package that is required for run time. Once you use the above command, enjoy the terminal text or go grab yourself a drink, this will take a couple of minutes
  4. Once this is finished, you’re probably looking at your project folder and thinking…where’s Cypress? Other than a new node_modules folder, which you can ignore, for now, there’s nothing new. But we can fix that quickly with a simple command to initialise Cypress

    npx cypress open

    npx isn’t a typo, it’s something bundled with npm and it provides us a much quicker way to open Cypress. You’ll notice when you run this, you’ll get a line of text in your terminal telling you that it’s the first time you’ve run Cypress for this project. It will then go away and finish setting up a load of things, and once done, Cypress is alive! We have a fancy new dashboard, but more importantly, we have a new folder and files in our project that we can begin to use.
    We will definitely be coming back to that new dashboard, but for now, let’s jump back to the code and take a look at what we have.

    First off you’ll see a cypress folder which is where we’ll be working for the next few articles. Inside it will be split into the following folders:

    cypress/fixtures
    cypress/integration
    cypress/plugins
    cypress/support

    And the following config file will be in your root folder:

    foldername/cypress.json

    The ‘Integration’ folder is where your tests will live. Folders can be created inside of this to structure tests how you’d like, but the tests must always be inside the ‘Integration’ folder. Cypress will automatically pick up any .js files in this folder and add them to the dashboard. If you are running via the Cypress CLI then they will be picked up automatically if you are running all tests and not using custom commands.

    The ‘Fixtures’ folder will contain any data in JSON format that you need. These can be request responses or other custom data, but it must be in JSON format.

    ‘Plugins’ folder will contain a single ‘index.js’ file by default, which for 90% of testing tasks will be all you need. In this index file, you will add any plugins that you want to ‘require’ at a global level

    Finally, ‘Support’ is similar to ‘Plugins’ in that it will contain an index file, this time used for declaring global modules that you don’t want to import on a per-file basis, and a commands file that you can use to create custom Cypress commands. These are useful for extending Cypress or wrapping methods that you might want to use

    We will go over each of these in more detail as this series progresses, but for now, so not to overwhelm you, don’t worry about them. Except for the integration folder, as that is where we will be creating our first test! To do so, inside the folder, add a new file, call it whatever you like but for the sake of this article, we’ll call it “FirstTest.spec.js”. It’s important to have spec in the file name as otherwise, Cypress won’t pick it up as a valid test file and won’t see any tests inside of it.
  5. Now we have our test file, let’s write a basic test. What does a Cypress test look like and what does it all mean?
describe('My First Tests', () => {
    it('Visiting Google displays the correct title', () => {
        cy.visit('https://google.co.uk')
        cy.title().should('contain', 'Google');
     })
})

A very complex test I’m sure you’ll agree. But congratulations, you’ve written your first Cypress test. So what’s it doing?

If you’re not familiar with JavaScript testing, then the ‘describe’ and ‘it’ keywords will be new. If you have used them, you’ll recognise them as being part of Mocha, a testing framework that allows you to write and organise easily readable tests. ‘Describe’ and ‘It’ is spec-style naming for your tests, that allow you to use plain English as opposed to method names as you’d use with Nunit in C#.
Describe is the name of your spec, or test suite if you will. If we were being a bit better with the naming of our test suite, we might say describe(‘Google Home Page’).
‘It’ is the name of the test within that test suite, and again takes a string in plain English to clearly describe your test. We’ve actually gone with a pretty good test title in the example above, to demonstrate how you might use it.

Inside the test itself, you’ll notice and test steps start with the cy keyword. Like in our Selenium series, you’d often use the driver keyword, Cypress has its own in the form of cy.

The test steps are pretty basic but you’ll notice the second one contains our assert, and we’re simply checking that the title of the page is as we’d expect.

Remember that dashboard you saw earlier, open that and you’ll notice that your fancy new test file and test are showing in there. By default, Cypress watches for any file changes in that folder so will automatically pick it up.

If you click on your test file, you’ll see a new window open which is the Cypress browser running your test. It will be over before you know it and you’ll see lots of lovely green because your test has passed. Congratulations!

That was a very brief introduction to Cypress, and dealt with the tedious task of setup and explaining the basics like folder structure etc. Next article, we’ll be jumping straight into the joys of page objects in Cypress and improving our tests, beefing them up a bit and changing the basic Cypress config

I hope this was helpful, and as always, please do give me feedback if you disagree with anything or think I’ve missed something.