End-to-end testing
Cypress is one of the options when it comes to end-to-end (E2E) testing. Cypress is an all-in-one testing framework focused on E2E testing meaning that you don’t have to install 10 different things to get your test suite set up. You can write your first passing test in minutes without any configuration with the help of Cypress’ API which is easy to read and understand. It runs tests as fast as your browser can render content which also makes test-driven development possible. You’ll also profit from the time travel feature or the extensive debugging capabilities with Chrome DevTools. Of course you can also use it with Gatsby and this guide will explain how.
In order to run Gatsby’s development server and Cypress at the same time you’ll use the little helper start-server-and-test. If you’re already using react-testing-library for unit testing you might want to install cypress-testing-library, too. This way you can use the exact same methods you used with react-testing-library
in your Cypress tests. Install the following packages to your devDependencies
:
npm install --save-dev cypress start-server-and-test
We also want the urls used by cy.visit()
or cy.request()
to be prefixed hence you have to create the file cypress.json
at the root of your project with the following content:
{
"baseUrl": "http://localhost:8000/"
}
Last but not least you add additional scripts to your package.json
to run Cypress:
{
"scripts": {
"develop": "gatsby develop",
"cy:open": "cypress open",
"test:e2e": "start-server-and-test develop http://localhost:8000 cy:open"
}
}
Run test:e2e
in your command line and see Cypress running for the first time. A folder named cypress
will be created at the root of your project and a new application window will pop up. Cypress’ getting started guide is a good start to learn how to write tests!
Important note: If you are running Gatsby with the --https
flag, whether using your own or automatically generated certificates, you will also need to tell start-server-and-test
to disable HTTPS certificate checks (otherwise it will wait forever and never actually launch Cypress. You do this by passing in an environmental variable: START_SERVER_AND_TEST_INSECURE=1
. start-server-and-test docs.
This means your test:e2e
script would look like this:
"test:e2e": "START_SERVER_AND_TEST_INSECURE=1 start-server-and-test develop http://localhost:8000 cy:open"
Continuous Integration
If you want to run Cypress in Continuous Integration (CI) you have to use cypress run
instead of cypress open
:
{
"scripts": {
"develop": "gatsby develop",
"cy:open": "cypress open",
"cy:run": "cypress run",
"test:e2e:ci": "start-server-and-test develop http://localhost:8000 cy:run"
}
}
Please read the Cypress’ official documentation on CI if you want to know how to setup Travis or GitLab with Cypress.
Edit this page on GitHub