This article goes over how to perform a Google search using the Cypress end-to-end (E2E) test runner. See the YouTube video:
Prerequisites
Install
Install cypress with npm or yarn:
npm install cypress
Open
Open Cypress:
npx cypress open
The directories will be created:
tree cypress -L 1
cypress
├── fixtures
├── integration
├── plugins
└── support
4 directories, 0 files
To run a test, click on the test file:
Example
Create file cypress/integration/example.js
:
touch cypress/integration/example.js
Write the test:
it('should pass', () => {
expect(true).to.equal(true);
});
Click on the test so it runs in a new browser window:
Cypress uses Mocha as the test runner and Chai as the assertion library.
Google Search
Create file cypress/integration/google-search.js
:
touch cypress/integration/google-search.js
Use visit
to open a page:
cy.visit('https://www.google.com');
Use get
to select a DOM element:
cy.get('input[name="q"]');
The querying behavior is similar to jQuery’s
$()
.
Click Open Selector Playground
to try out different selectors:
Click an element or use the browser Inspect
tool to get a good selector:
Use type
to input text and keyboard actions:
cy.get('input[name="q"]').type('remarkablemark{enter}');
{enter}
types the Enter key.
An alternative to typing the Enter key is to submit the form:
cy.get('form').submit();
Or to click the search button:
cy.get('input[value="Google Search"]').first().click();
Use invoke
to get the first search URL:
cy.get('#search a')
.first()
.invoke('attr', 'href')
.then((href) => console.log(href));
then
is used to yield the promise value since the command is asynchronous.
Code
describe('Google Search', () => {
it('loads search page', () => {
cy.visit('https://www.google.com');
});
it('searches for `remarkablemark`', () => {
cy.get('input[name="q"]').type('remarkablemark{enter}');
});
it('gets first search result', () => {
cy.get('#search a')
.invoke('attr', 'href')
.then((href) => console.log(href));
});
});