Cypress hooks carry out certain operations before or after each test. They are helpful to set conditions that we want to run before a set of tests. They also help clean after a set of tests are executed.
Some of the most common hooks are the following:
before()
beforeEach()
after()
afterEach()
Let’s discuss the before()
and beforeEach()
hooks in detail.
before()
hookThe before()
hook is run once before we start the execution of the first test. It might have a few setup steps we need to perform before we get started with the test execution.
Let’s assume we have to write a couple of tests in which we have to visit a specific page URL. After a couple of tests, opening the URL page action will get repetitive and therefore take a lot of resources.
So, a before()
hook is used as a solution over here.
before(function() {
// Steps we need to perform before we get started with the test execution.
})
OR
before(function namedFunction() {
// Steps we need to perform before we get started with the test execution.
})
OR
before('some description', function() {
// Steps we need to perform before we get started with the test execution.
})
before(function() {cy.visit('/')})it('test 1', () => {// rest of your test})it('test 2', () => {// rest of your test});
We use a before()
hook in the code block above. This opens up our URL page before all our tests are executed.
beforeEach()
hookIf we want to isolate our tests so they don’t affect each other, we use the beforeEach()
block to group these test steps together. This is done if we want to execute some steps before each test case.
This helps us gain overall test stability. However, it might need us to structure our tests in a certain way.
beforeEach(function() {cy.visit('/')});ORbeforeEach(function namedFunction() {cy.visit('/')});ORbeforeEach('some description', function() {cy.visit('/')})it('test 1', () => {// rest of your test})it('test 2', () => {// rest of your test});
Just like the before()
block, the beforeEach()
block can take three kinds of parameters:
The above code will open and visit the URL before executing each test.
We can find a working example containing a few concepts discussed here:
describe('My App', () => { beforeEach(() => { cy.visit('/'); }) it('it has a title', () => { cy.get('h1').contains('Welcome'); }); it('it has a red color element', () => { cy.get('li') .should('have.css', 'color') .and('eq', 'rgb(255, 0, 0)') }); });
Note: If you have opened this shot in the incognito mode, please enable the "Allow all cookies" option in your browser. Otherwise, you might get an error in the "Output" tab.
beforeEach
cypress hook that redirects the user back to the homepage before each test runs. We use the visit
command for this.h1
tag and contains the Welcome
keyword. li
element has the color red.