elementinn-blog
elementinn-blog
Cypress tests
1 post
Don't wanna be here? Send us removal request.
elementinn-blog · 6 years ago
Text
Cypress testing - a swift, less hassle and awesome tests!
What is it about:
A little bit about Cypress.io. This is a new javascript end-to-end testing tool. Its fast, easy and awesome. For more details, please have a look on their website Cypress.io  As a testing professional, I would like to briefly explain how I am going to use this tool and write simple tests. The first thing I have done is, I have downloaded and install cypress from their website. I have already installed npm-node.js in my system. Before jumping into cypress, knowledge of javascript, jquery is highly desirable.
cd /your/project/path
npm install cypress --save-dev
see here for original cypress installation steps >> installation step
Please set the following under settings>configuration if you want the test runner to run the test immediately after making changes.
watchForFileChanges: true
System configuration :
Windows 8.1 Pro, i5 3.10 GHz processor, 8GB RAM, 128 GB SSD drive 
Writing my own very simple cypress tests:
Let us do some more groundwork before writing the tests. Install a js editor of your choice. I have used Atom.js editor for creating the tests. Ensure you have cypress.json file in the project root folder. Then navigate to integration/examples folder or create a folder of your choice. Open the created folder from the js editor. Now create a test_spec.js file or you give an appropriate name of the file with extension .js and save under that location.
Let’s start:
1) First Test- is to compare very simple input values as below, write the below test in the test_spec.js file and save. Click on the ' test_spec.js' it will open a browser and start running the test and see the test result got passed
describe('Compare two input values', function() {  it('Test to compare two inputs values', function() {       var first_input =100;       var second_input = 100;         expect(first_input).to.equal(second_input)     cy.log(first_input + second_input)          }) })
Tumblr media
2)Now we will test the selection of a 'checkbox' and verify the display of a message after selection:
describe('Checkbox Selection test', function() { it('Check if the checkbox is selected successfully and verify the message',  function() {   cy.visit('http://www.seleniumeasy.com/test/basic-checkbox-demo.html')   cy.get('#isAgeSelected').check()   cy.get('#txtAge')   .invoke('text')   .then(text => {      const someText = text;      cy.log(someText);      expect(someText).to.contain('Success - Check box is checked')                 });             })         })
Tumblr media
3) How to test an 'api' and verify values received using cy.request() ?
describe('Verify the Api Get method', function(){ it('Verify the 'userid', id and title is received in response', function(){ cy.request('GET', 'https://jsonplaceholder.typicode.com/posts/42') .then((response) => { // response.body is automatically serialized into JSON  expect(response.body).to.have.property('userId', 5) // true  expect(response.body).to.have.property('id', 42) // true     })   }) })
Tumblr media
4) How do we test an 'alert' message and its text using cy.stub ()?
     describe('Test an alert and the text displaying', function() {      it('Verify alert and its text content', function(){      cy.visit('http://www.seleniumeasy.com/test/javascript-alert-box-demo.html')              const stub = cy.stub()               cy.on ('window:alert', stub)               cy                .get('button').contains('Click me!').click()                    .then(() => {                     expect(stub.getCall(0)).to.be.calledWith('I am an alert box!')                        })              })      })
Tumblr media
5) Cypress test using a cy.wrap() and object passed into the wrap method:
describe('Object passed into Wrap method', function() { it('Check if the object passed into Wrap method and call BMI ', function() { const getBMI= (weight, height) => { var weight ; var height ; var hghtintoMtr = height / 100; var squareHght = hghtintoMtr * hghtintoMtr; var bmi = parseFloat(weight/squareHght).toFixed(2) ; return bmi } cy.wrap({ bmi: getBMI }).invoke('bmi', 78, 176).should('eq', '25.18') // true cy.wrap({ bmi: getBMI }).invoke('bmi', 85, 181).should('eq', '25.95') // true }) })
Tumblr media
6) Conditional testing using cypress, calling a random js function and check the message.
describe("Conditional testing, check success or fail", () => {        it('Verify the success or failure test', function() {          const message = myMessage();          if (message == "success"){            expect(message).to.equal("success");          }else {            expect(message).to.equal("fail");          }        })
   })
   function myMessage(){      var words = ['success', 'fail'];      var word = words[Math.floor(Math.random() * words.length - 1)];      return word;    }
Tumblr media
7)Using cypress test the ‘toast’ message
describe('Test the toast message', function() {   it('Verify the the two toast message', function() {    cy.visit('https://www.primefaces.org/primeng/#/toast')   cy.get('button[label="Success"]').find('span').contains("Success").click({force:true})    cy.wait(1000)    cy.get('div.ui-toast-detail').invoke('text')     .then((text)=>{       const toastText = text;       expect(toastText).to.equal("Order submitted");     })    cy.wait(1000)     cy.get('button[label="Error"]').find('span').contains("Error").click({force:true})     cy.wait(1000)     cy.get('.ui-toast-message-content').find('div').find('div').contains("Validation failed").invoke('text')      .then((text)=>{        const toastText = text;        expect(toastText).to.equal("Validation failed");      })   }) })
Tumblr media
8)Cypress test using 'before', route() and XHR post method to check the status 200 received and text:
describe('XHR POST form submission test', () => {  before(() => {      cy.visit('https://resttesttest.com/')    })    it('Verify whether the successfull submits of an XHR POST method on form submission', () => { cy.wait(3000)  cy.get('#httpmethod').select('POST') cy.get('#urlvalue').clear() cy.get('#urlvalue').type('https://httpbin.org/post') cy.get('#addprambutton').click() cy.get('.input-medium.fakeinputname:last').type('Sample', {force: true}) cy.get('.input-xlarge.realinputvalue:last').type(' SomeNameHere ', {force: true}) cy.server();            cy.route('POST', '/post').as('paramform') // note that the route needs to match trailing slashes            cy.get('#submitajax').click()                .wait('@paramform')                .its('status').should('equal', 200)        .then(() => {            cy.get('#statuspre').contains('HTTP 200 OK').should('exist')            cy.get('#outputpre').contains('SomeNameHere').should('exist')        })    }) })
9) Using cy.request(), cypress test to verify the receive the response status 200
describe('Verify response 200 is received', function(){ it('Check whether the response 200 is received', function(){ cy.request('GET', 'https://jsonplaceholder.typicode.com/posts/42') .then((response) => { expect(response.status).to.eq(200)           })      }) }) 
Tumblr media
10)Cypress test using a 'writeFile' method to write json data to a file in the following location:
Tumblr media
describe('Write to file and verify data', function(){ it('Check whether the writing to file and verify the json data', function(){ cy.writeFile('/path/to/data.json', {name: 'Apple2', email: '[email protected]'}) .then((user) => { let jsonUser = JSON.parse(user) expect(jsonUser.name).to.equal('Apple2') expect(jsonUser.email).to.equal('[email protected]')       })     })  })
2 notes · View notes