Basics of Cypress
Hello everyone! I recently started a front-end engineering internship, and one of the most important things to learn to get a job as a front-end engineer, is learning a testing framework like Cypress and Jest.
Cypress is not easy to learn at first, but once you practice writing testing specs, you’ll really get familiar with how it works, at times lol
- That’s what we are going to do today, I simply created a new project with
npx create-next-app or npx create react-app.
- Then we are going to install cypress
npm install cypress --save-dev
- Once you run npx cypress open , it will open this window:
- Once you do, you’ll see a cypress folder in your project after running npx cypress open.
- Let’s create our first cypress test by running this command in your terminal.
touch {your_project}/cypress/integration/sample_spec.js
- Or simply create a new file
sample_spec.js
incypress/integration
- At the cypress window that was fired up once you ran the command npx cypress open, you’ll have access to the
sample_spec.js
Now it’s time to write our first test. We’re going to:
- Visit a web page:
describe('My First Test', () => {it('Renders page successfully', () => { cy.visit('http://localhost:3000/') })})
2. Query for an element. Here we will use the .get()
- by Selector:
it("Checks for existence of 'div'", () => { cy.get('div')});
3- Check if it’s visible using .should() :
it("Checks for existence of 'div'", () => { cy.get('div') .should('be.visible')});
4- Chaining using .and() to check for attributes:
it("Checks for existence of 'a' tag", () => { cy.get('a') .should('be.visible') .and("have.attr", "href");});
5- Check the parent and children elements .parent() and .children()
Let’s create a simple component that renters a ul with social media links like this:
- Add these lines of code into
sample_spec.js
file:
it("Checks for element's parent", () => { cy.visit('http://localhost:3000/') cy.get('#social-list') .parent().should('match', 'div')})it("Checks for element's childern" , () => { cy.visit('http://localhost:3000/') cy.get('#social-list') .children().should('match', 'a')})
6- Get by attribute: Let’s add an attribute to the a tag
<a href='https://www.google.com/' aria-label='social-list'>
<li>Google</li>
</a>
Now we are going to get the tag, check if it’s <a> and that it’s visible
it("Get a tag by attribute", () => { cy.get("[aria-label=social-list]") .should("match", "a") .should('be.visible')});
Let’s also check if that <a> tag has Google in it:
it("Get a tag by attribute that it contains 'Google'" , () => { cy.get("[aria-label=social-list]") .contains('Google')});
Resources
- Cypress docs