{"id":9684,"date":"2023-08-29T19:08:59","date_gmt":"2023-08-29T19:08:59","guid":{"rendered":"https:\/\/testgrid.io\/blog\/?p=9684"},"modified":"2024-08-29T15:47:03","modified_gmt":"2024-08-29T15:47:03","slug":"cypress-assertions","status":"publish","type":"post","link":"https:\/\/testgrid.io\/blog\/cypress-assertions\/","title":{"rendered":"Cypress Assertions"},"content":{"rendered":"\n<p>Cypress Assertions: First we will try to understand <strong>what exactly is Cypress? and why is it used?<\/strong><\/p>\n\n\n\n<p>So, Cypress is a new age Test Automation tool used for Web application automation, we can validate different UI checks and screens of an application. Cypress speeds up the execution as compared to performing this manually. When we perform Web application testing manually we tend to miss attention to details , whereas with Cypress we get all the testcases formed in the form of scripts and it covers everything in detail.<\/p>\n\n\n\n<p>Cypress is just like a robot who works on instructions given by a test developer using scripting language. It clicks on buttons, links and fetches data from the UI for further validation. By providing a set of instructions to cypress we can navigate through the website and test all possible scenarios both positive as well as negative.<\/p>\n\n\n\n<p>Also Read:  <a href=\"https:\/\/testgrid.io\/blog\/how-to-check-if-an-element-exists-or-not-using-cypress\/\" data-type=\"URL\" data-id=\"https:\/\/testgrid.io\/blog\/how-to-check-if-an-element-exists-or-not-using-cypress\/\">Check if an element exists or not using Cypress<\/a><\/p>\n\n\n\n<p>While executing the test, Cypress works in two ways: headed and headless. When we give commands for headed execution, you will see a new window getting open with options of selecting web browsers. From there you can select chrome or electron and kick off your automation run. Whereas when we perform execution in headless mode we start the execution by defining @tags which will help Cypress to understand which test cases need to be executed and which can be skipped.<\/p>\n\n\n\n<p>We can define <a href=\"https:\/\/testgrid.io\/blog\/cypress-with-cucumber\/\" data-type=\"link\" data-id=\"https:\/\/testgrid.io\/blog\/cypress-with-cucumber\/\">Cypress framework using cucumber<\/a>, we can create feature files which will be having all the test steps defined in Gherkins and for each step there will be step definition, we will be having a POM (Page object model) using that we will be keeping all page related identifiers at one place . Inside the Fixture folder we will be keeping all our test data, we will keep general utilities in the Utility folder which will be getting called out in step definitions. For reporting we can use allure report or HTML report.<\/p>\n\n\n\n<p><em>For this article we are targeting to understand Cypress assertion so first we will try to understand:<\/em><\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What are Assertions?<\/strong><\/h2>\n\n\n\n<p>In general English \u201ca statement that says you strongly believe that something is true\u201d\u2019, so for implementing this in Cypress we have two libraries \u201cChai\u201d and \u201cJest\u201d, using these libraries we can access multiple methods which we can use values and behaviour of the program or code.<\/p>\n\n\n\n<p>Assertions usually evaluate in boolean format in \u201cTrue\u201d or \u201cFalse\u201d, based on which we make a decision if the test case is getting passed or failed or sometimes we define other flows based on the outputs which we are getting from assertions. If we do not use assertions in the code it will become very difficult to identify the problem plus validate the functionality which should be there on application. If we are expecting a button to be there on the UI and it should be enabled for that we will be needing assertions.<\/p>\n\n\n\n<p>In Cypress we have Chai Library, which helps in providing multiple assertion functions including \u201cShould\u201d and \u201cexpect\u201d which are the two most commonly used assertion functions.<\/p>\n\n\n\n<p><strong>In the following sections, we will explore the different types of Cypress asserts and provide examples of each.<\/strong><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Types of Cypress Assertions<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">BDD Assertions in Cypress<\/h3>\n\n\n\n<p>BDD (Behavioral driven development) are written with Keywords such as Given\/When\/Then\/And&nbsp; which define the expected behaviour in very easy and understandable language, we use SHould and expect function for implementing these assertions.<\/p>\n\n\n\n<p>1. <strong>\u201c.should()\u201d:<\/strong><\/p>\n\n\n\n<p>The `.should()` command is used to make various assertions about elements on the page. We will be providing a string argument describing the condition we are checking and a chaining function that specifies the assertion. We can have multiple \u201cshould\u201d assertions chained together for validating complex functionality and other aspects of the web application.<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>cy.get('button').should('be.visible');  \/\/ Checks if the button is visible\ncy.get('input').should('have.value', 'Hello');  \/\/ Checks if the input has the value \"Hello\"\n\ncy.get(\"#element\").should(\"have.class\", \"some-class\"); \/\/ Checks if element has a specific class\n\ncy.get(\"#element\").should(\"be.hidden\"); \/\/Checks if element is hidden\n\n<\/code><\/pre>\n\n\n\n<p>Real time example:<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>When(\"I select {string} option from {string} dropdown\", (option, placeholder) =&gt; {\n  cy.get(`input&#91;placeholder=\"${placeholder}\"]`)\n    .click()\n    .then(() =&gt; {\n      cy.get(\"li\").contains(option).click();\n    })\n    .then(() =&gt; {\n      cy.get(`input&#91;value=\"${option}\"]`).then((element) =&gt; {\n        cy.get(element).should(\"have.value\", option);\n      });\n    });\n});\n<\/code><\/pre>\n\n\n\n<p>2. <strong>\u201c.should(&#8216;not&#8217;)\u201d:<\/strong><\/p>\n\n\n\n<p>we&nbsp; can use `.should(&#8216;not&#8217;)` to negate assertions or means to validate negative assertions.<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>cy.get('button').should('not.be.disabled');\/\/assertion for validating disable button<\/code><\/pre>\n\n\n\n<p>3. <strong>\u201c`.should()` with Chaining Functions\u201d<\/strong><\/p>\n\n\n\n<p>You can use chaining functions ( when we want to club multiple operations) for more complex assertions and use their methods to specify the expectation.<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>cy.get('ul')\n  .should('have.class', 'active')\n  .and('have.attr', 'data-testid', 'my-list')\n  .and('contain', 'List Item 1');\n \n<\/code><\/pre>\n\n\n\n<p>4. \u201c.<strong>expect()<\/strong>\u201d:<\/p>\n\n\n\n<p>The `.expect()` function is used for more complicated assertions, and it is often used with chaining commands. It&#8217;s similar to `.should()`, but it allows you to make multiple assertions on the same subject.<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>cy.get('p').should('have.length', 3).expect($p =&gt; {\n    \/\/ Custom assertions using jQuery methods on the selected elements\n    expect($p.eq(0)).to.contain('First paragraph');\n  });\nexpect(\"expectedText\").to.have .text(\"actualText\") ; \/\/ asserting Expect to validate text or number\nexpect(\"value\").to.be.a(\"string\"); \/\/Asserting the data type of the actual value\n<\/code><\/pre>\n\n\n\n<p>Real time example:<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>When(\"The button {string} is {string}\", (text, status) =&gt; {\n  cy.get(`button:contains(\"${text}\")`).then(($btn) =&gt; {\n    if (status === 'enabled') {\n      expect($btn).not.to.have.class('Mui-disabled');\n      expect($btn).not.to.have.attr('disabled');\n    } else {\n      expect($btn).to.have.class('Mui-disabled');\n      expect($btn).to.have.attr('disabled');\n    }\n  });\n});\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>TDD Assertions<\/strong> in Cypress<\/h2>\n\n\n\n<p>TDD (Test Driven Development), in TDD we follow the approach first test then develop. And the coding style which we follow is \u201cArrange\/Act\/Assert (AAA)\u201d, Arrange refers to setting up all the preconditions which are required for testing, Act refers to perform the actions which are required for testing and Assert refers to the verification of outcomes which we are getting , the function which is used for performing assertion is assert()<\/p>\n\n\n\n<p>1. `<strong>.assert()<\/strong>`:<\/p>\n\n\n\n<p>The `.assert()` command is similar to `.should()` and is used for making assertions about elements and properties. When it gets into details we need .assert() to fetch and validate.<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>cy.get('input').assert('have.attr', 'type', 'email');  \/\/ Checks if the input has the \"type\" attribute with value \"email\"\ncy.get(\"#element\").then(($el) =&gt; {\n  assert.isTrue($el.hasClass(\"some-class\"))\n}); \/\/asserting the class check for element\ncy.get(\"#element\").then(($el) =&gt; {\n  assert.isTrue($el.is(\":visible\"))\n}); \/\/asserting a check for visibility of element\n\ncy.get(\"#element\").then(($el) =&gt; {\n  assert.isTrue($el.is(\":hidden\"))\n}); \/\/ asserting that an element is hidden\ncy.get(\"#element\").then(($el) =&gt; {\n  assert.equal($el.attr(\"type\"), \"text\")\n}); \/\/ asserting element has a specific value\n<\/code><\/pre>\n\n\n\n<p>&nbsp;&nbsp;Real time example:<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>const checkStatus = () =&gt; {\n    if (loopCount &gt;= 10) {\n      assert.fail('Exceeded maximum number of attempts to check pipeline status');\n    }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Chai-jQuery Assertions<\/strong> in Cypress<\/h3>\n\n\n\n<p>Chai and JQuery assertions are made up of Chai &amp; JQuery, JQuery is used to identify and locate web elements on the page Chai helps in making assertions about their current state and availability. It validated the property of the web elements present on the page using .Should().<\/p>\n\n\n\n<p>This assertion is widely used in automation frameworks, first we need to include the Chai-Jquery dependency.<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>import 'cypress-jquery';<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">Few Examples of Chai-JQuery assertions:<\/h4>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>\/\/ Check if element with a specific class exists or not\ncy.get('.element').should('exist');\n\n\/\/ Check if element is visible or not\ncy.get('.element').should('be.visible');\n\n\/\/ Check if element contains specific text or not\ncy.get('.element').should('contain', 'Hello, World!');\n\n\/\/ Check if an element has a specific CSS class\ncy.get('.element').should('have.class', 'active');\n\n\/\/ Check if input field has a specific value\ncy.get('input&#91;name=\"password\"]').should('have.value', 'john_doe');\n\n\/\/ Check if element has a specific attribute\ncy.get('a&#91;href=\"\/home\"]').should('have.attr', 'target', '_blank');\n<\/code><\/pre>\n\n\n\n<p>Real time example:<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>When(\"I click {string} option of side menu\", (text) =&gt; {\n  cy.get('&#91;role=\"button\"]').contains(text).should(\"have.text\", text).click();\n});\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Sinon-Chai Assertions<\/strong> in Cypress<\/h3>\n\n\n\n<p>Sinon-Chai assertion is one of the most widely used assertion libraries in Cypress UI automation framework. Cypress has multiple key features but one of them is the most important as it reduces the external dependencies in a controlled environment using simulated behaviour. We use this assertion to manage the stub calling and keeping count of it in order to streamline the simulated behaviour.&nbsp;<\/p>\n\n\n\n<p>Few examples of the assertions which we use in stubbing:<\/p>\n\n\n\n<p>Assert to validate a stub has been called for a number of times.<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>const obj = {\n  teststub() {\n    console.log(\"hello world welcome\")\n  },\n}\ncy.stub(obj, \"myMethod\")\nobj.teststub()\nobj.teststub()\nobj.teststub()\n\nexpect(obj.teststub).to.have.callCount(5)\n\/\/ assertion to validate a stub has been called for a number of times.<\/code><\/pre>\n\n\n\n<p>Assert to check a spy has been called on test<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>const spy = cy.spy()\nconst test= { method: spy }\nobj.method()\nexpect(spy).to.have.been.calledOn(test)\n\/\/ assert to check a spy has been called on test\n\n\n<\/code><\/pre>\n\n\n\n<p>Assertion to validate a stub has not been called<\/p>\n\n\n\n<pre class=\"wp-block-code has-white-color has-black-background-color has-text-color has-background\"><code>const obj = {\n  myTest(arga: string, argb: string) {\n    console.log(arga, argb)\n  },\n}\ncy.stub(obj, \"myTest\")\nexpect(obj.myTest).to.not.have.been.called\n\/\/ assertion to validate a stub has not been called\n<\/code><\/pre>\n\n\n\n<p><strong>Conclusion:<\/strong><\/p>\n\n\n\n<p>So after discussing all the assertions in detail for cypress the conclusion is that with the help of a rich and resourceful library provided by Cypress, we can validate, check and identify issues on web applications using automation conveniently and with speed. It can be implemented quickly and execution of this automation is fairly simple, any person with limited knowledge can perform execution and fetch the results using reports. With Assertions we can guarantee the validation of each and every object which is present on the application.<\/p>\n\n\n\n<p>Also Read this detailed <a href=\"https:\/\/testgrid.io\/blog\/cypress-testing\/\" data-type=\"link\" data-id=\"https:\/\/testgrid.io\/blog\/cypress-testing\/\">guide on Cypress Test Automation <\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Cypress Assertions: First we will try to understand what exactly is Cypress? and why is it used? So, Cypress is a new age Test Automation tool used for Web application automation, we can validate different UI checks and screens of an application. Cypress speeds up the execution as compared to performing this manually. When we [&hellip;]<\/p>\n","protected":false},"author":21,"featured_media":9691,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"footnotes":""},"categories":[2078],"tags":[],"class_list":["post-9684","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-cypress"],"acf":[],"images":{"medium":"https:\/\/testgrid.io\/blog\/wp-content\/uploads\/2023\/08\/Cypress-assertion-300x157.jpg","large":"https:\/\/testgrid.io\/blog\/wp-content\/uploads\/2023\/08\/Cypress-assertion-1024x536.jpg"},"_links":{"self":[{"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/posts\/9684","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/users\/21"}],"replies":[{"embeddable":true,"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/comments?post=9684"}],"version-history":[{"count":10,"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/posts\/9684\/revisions"}],"predecessor-version":[{"id":12333,"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/posts\/9684\/revisions\/12333"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/media\/9691"}],"wp:attachment":[{"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/media?parent=9684"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/categories?post=9684"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/testgrid.io\/blog\/wp-json\/wp\/v2\/tags?post=9684"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}