Before writing our test, we will first be activating the IntelliSense feature provided by Cypress. IntelliSense offers intelligent code suggestions (which includes code defination, code example and a link to the documentation) directly into the IDE while writing tests. You can learn more about it from here. Now there are two ways to do it:
- Mention at the start of every spec file:1/// <reference types="cypress" />
- Create a file called jsconfig.json at the project root level with the content:1
2
3
4
5
6{
"include": [
"./node_modules/cypress",
"cypress/**/*.js"
]
}
Point 1 is a repetitive task and has to be repeated for every test file whereas point 2 is a one-time activity, so I would recommend point 2.
The next step is to create a test file(TC01.spec.js) inside the integration folder where we will be automating the below mentioned scenario step by step.
- Go to https://www.wikipedia.org/
- Validate the Page Title
- Search for Google Wiki Page
- Validate that Google wiki page is successfully displayed after search
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | describe('Search for Google Wiki page from Wikipedia website', () => { before(() => { cy.visit('https://wikipedia.org') }) it('Validate Page Title', () => { cy.title().should('eq', 'Wikipedia') }) it('Search for Google Wiki Page', () => { cy.get('#searchInput').type('google') cy.get('button[type="submit"]').click() }) it('Validate Google Wiki Page has opened', () => { cy.get('h1#firstHeading').contains('Google') cy.title().should('eq', 'Google - Wikipedia') }) }) |
Let’s try to understand the written code step by step:
1. describe and it comes from the mocha framework. Describe block can be understood as the collection of tests or a test suite, whereas it block represents a single test or a test case.
2. before() runs once before all the test cases hence we wrote cy.visit() inside it since all our test cases need the website to be opened before they could be run.
3. first it block (Validate Page Title) – Here we are using the cypress command cy.title() to get the title of the current webpage. And then we are using should(‘eq’, ‘Wikipedia’) which basically translates into title should be equal to Wikipedia.
4. second it block (Search For Google Wiki Page) – The cypress command cy.get(‘locator’) is used to access any element on the webpage. type(‘text’) is used for typing texts into the element. click() is used for clicking the element.
5. third it block (Validate Google Wiki Page has Opened) – cy.get(‘h1#firstHeading’).contains(‘Google’) checks that the first heading text of the current web page is Google. cy.title().should(‘eq’, ‘Google – Wikipedia’) checks that the title of the current web page is Google – Wikipedia.
Do check out 🙂
Github:Â https://github.com/alapanme/Cypress-Automation
All Cypress Articles: https://testersdock.com/cypress-tutorial/