Showing posts with label Automation. Show all posts
Showing posts with label Automation. Show all posts

Things included in Package.json file

 


  • dependencies
    • cypress version
  • commands to run cypress test
    • cypress:open : "cypress open"
  • plugins
    • mochawesome
  • project name
  • project version

Things Included in Cypress.config.js file


What is cypress.config.js file ?


  • The cypress.config.js file is a configuration file used with Cypress, a popular end-to-end testing framework for web applications. 
  • This file allows you to configure various settings and options for your Cypress tests. 
  • Here are some of the properties that can be included in a cypress.config.js file:
    • baseUrl
    • defaultCommandTimeout
    • viewPortWidth
    • viewPortHeight
    • env configurations
      • username
      • password

Ex:
module.exports = {
  baseUrl: 'http://localhost:3000', // Example base URL
  viewportWidth: 1366,
  viewportHeight: 768,
  env: {
    NODE_ENV: 'development',
  },
  defaultCommandTimeout: 4000,
  execTimeout: 6000,
  pageLoadTimeout: 10000,
  chromeWebSecurity: false,
  ignoreTestFiles: '**/examples.spec.js',
};

Handle Alerts in Cypress

 Alert : 

Display a message to the user with an OK button. The user must click OK to dismiss the alert


Here is the way to verify that the alert is clicked


cy.on('window:alert' ,  (str) => {
    expect(str).to.eq.('Text value')
})

Confirm Alert

Display a message to the user with the OK and Cancel buttons. The user can choose to confirm or cancel the action.


Here is the way to verify that the Cancel is clicked



cy.on('window:confirm', (text) => {

  expect(text).to.contains('Would you like to confirm?');

  return false;

});


Here is the way to verify that the Ok is clicked


cy.on('window:confirm', (text) => {

  expect(text).to.contains('Would you like to confirm?');

  return true;

});

Prompt Alert

In Prompt Alert user needs to enter text into the input field 


it('should trigger a prompt with a message', () => {

  cy.window().then(win => {

    cy.stub(win, 'prompt').returns('This is my answer.');

    cy.get('#prompt-button').click();

    cy.get('#prompt-answer').contains('Answer: This is my answer.');

  });

});

More Actions Using Cypress

These are some common actions used in Cypress
  •  Back (browser)
    • cy.go('back')
  • Forward
    • cy.go('forward')
  • Reload
    • cy.reload()
    • cy.reload(true) : without caching
  • Verify title content
    • cy.title().should('include' ,'Text')
  • Verify url content
    • cy.url().should('include', 'contactus')
  • Remove logs printing in the cypress log
    • cy.intercept({resourcetype : /xhr|fetch/} , {log : false})
  • Checkbox actions
    • check
      • cy.get('.element').check().should('be.checked')
    • uncheck
      • cy.get('.element').uncheck().should('not.be.checked')
    • check multiple checkboxes - using value attribute in inspect elements
      • cy.get('.element').check('option-1', 'option-2', 'option-3').should('be.checked')
  • Radio buttons
    • check
      • cy.get('.element').check().should('be.checked')
    • disabled 
      • cy.get('.element').should('be.disabled')
  • Drop down list
    • select item
      • cy.get('.element').select('value 1').should('have.value', 'value 1')
      • cy.get('.element').select('value 1').contains('value 1')
  • Verify background color
    • .... expect($element).to,have.css('background-color', 'rgb(0,255,0)')

Cypress Limitations


  • Multiple Tabs cannot be opened
  • Cannot run same time with different browsers
  • Cypress commands runs inside the browser
  • No support for native or mobile 
  • Support javascript only

  • Each test is bound to a single superdomIf we attempt to visit two diffrent supper domains in a single test it will fail  . But if we visit two subdomains it is works fine
    • Ex: cy.visit('www.abc.com')
      cy.visit ('www.yahoo.com')
    • cy.origin()





Alias in Cypress

What is an alias?

  • Assign a value for later use
  • We use the '@' symbol for the alias
  • It is a named reference or shortcut that represents a specific DOM element, or value, making it easier to reference and re-use
  • We can use aliases to store elements and interact with them later
  • It can be used to give a name to a series of actions or assertions
  • Alias helps to improve code maintainability

What is the method used for keeping aliases?

  • as
Provide a sample for usage of alias

  •   cy.get("#input-field").type("Hello, Cypress").as("inputAlias")
    •   cy.get("@inputAlias").should("have.value", "Hello, Cypress");
  • cy.get('.fixed').invoke('text').as('product')
    • cy.get('@product).its('length').eq(8)

 




Hooks in Cypress

Hooks in Cypress allow you to run setup and teardown code before and after your tests or test suites. This is useful for tasks like setting up test data, starting or stopping servers, logging in, and cleaning up after tests. Cypress provides several hooks that you can use in your testing framework.

  • before: This hook runs once before all the tests in your test suite.
  • beforeEach: This hook runs before each individual test case.
  • after: This hook runs once after all the tests in your test suite.
  • afterEach: This hook runs after each individual test case.

Cypress Interview questions

 Cypress interview questions are commonly asked during job interviews for roles related to web development and quality assurance. These questions focus on assessing a candidate's proficiency in using the Cypress testing framework, their knowledge of JavaScript, and their ability to write effective test scripts. Interviewers may also inquire about test automation best practices and strategies for handling common testing scenarios

General questions

  • What is Shadow dom and how to handle those in cypress ?

    1. Shadow DOM (Shadow Document Object Model) is a web standard that allows encapsulation of the DOM and CSS within a web component, preventing external CSS and JavaScript from affecting the component's internal structure. When working with Shadow DOM in Cypress, you might encounter challenges in selecting and interacting with elements within the shadow DOM. Cypress provides ways to interact with shadow DOM elements using its commands and APIs.

    2. cy.get('your-element-with-shadow-dom').shadow().find('element-inside-shadow-dom').click();

  • What is the architecture of Cypress ?

    • Cypress operates within the browser

    • Cypress is built using JavaScript and runs within a Node.js environment.

    • The Cypress server is a Node.js process that runs alongside your application and the Electron-based test runner.

    • It acts as an intermediary between your tests and the browser.

    • The server listens for commands from your test scripts, communicates with the browser to perform actions, and collects data and results.

  • Advantages of Cypress

    • Real-Time Interactive Testing
      • Cypress provides a real-time interactive test runner that displays your application alongside your test code.
      • You can see what's happening in the browser as your tests run, making debugging and troubleshooting easier.
    • Automatic Waiting
      • Cypress automatically waits for elements to appear and actions to complete before executing the next step in your test.
      • This eliminates the need for explicit and fragile waits or timeouts.
    • Time Travel Debugging
      • Cypress records every action and its consequences, allowing you to time-travel through your test execution.
      • You can pause and inspect the application's state at any point in the test, making it easier to diagnose issues.
    • Direct Access to DOM:
      • Cypress has direct access to the DOM, allowing you to interact with elements and events more effectively.
      • You can trigger DOM events, make assertions on DOM state, and manipulate the DOM directly.
    • Cross-Browser Support:
      • Cypress supports multiple browsers, including Chrome, Firefox, Edge, and Electron.
      • You can run your tests across different browsers to ensure compatibility
    • Headless Mode
      • Cypress can be run in headless mode for use in continuous integration (CI) and continuous deployment (CD) pipelines.
      • Headless mode allows you to execute tests without a graphical interface
    • Built-in Test Runner
      • Cypress includes a built-in test runner that provides a graphical user interface for running and managing tests.
      • It displays live previews of your application, making it easy to see the state of your application during testing.
    • Automatic Reload and Live Preview
      •  Cypress automatically reloads the browser when code changes are detected, making it seamless to develop and test simultaneously.
      • The live preview feature ensures that you always see the latest version of your application in the Cypress test runner.
    • Community and Plugins:
      • Cypress has an active and growing community.
      • There are many plugins and custom commands available to extend its functionality, making it highly customizable.
    • Great Documentation
      • Cypress provides comprehensive documentation, tutorials, and examples to help users get started quickly and troubleshoot issues effectively.
    • Consistent Test Results
      • Cypress provides consistent and reliable test results, reducing false positives and negatives in your tests.
    • Fast Test Execution
      • Cypress is designed for speed and efficiency, which helps reduce the overall time required for running tests.
    • Parallelization and Distributed Testing
      • With the Cypress Dashboard service, you can parallelize and distribute test runs across different environments, making it suitable for large-scale testing.
    • Continuous Development and Improvement
      • The Cypress team actively develops and maintains the framework, regularly releasing updates and new features.

  • Compare Cypress and Selenium

    • Cypress
      • Cypress runs directly within the browser and executes tests in the same JavaScript runtime as your application
      • It has access to the DOM and can directly interact with the elements on the page.
      • Cypress operates in a single tab, which means it cannot test multiple tabs or windows simultaneously.
      • It uses an event-driven architecture.
      • Cypress test needs to be written in javascript and typescript
      • Cypress has built-in support for Chromium-based browsers like Chrome and Electron.

        Cypress has automatic waiting for elements and actions, reducing the need for explicit waits and timeouts

        Cypress offers real-time interactive debugging with time-travel capabilities.

        Cypress has a built-in interactive test runner with a live preview of the application under test.

        Cypress is relatively easy to set up and get started with, especially for web applications.

    • Selenium
      • Selenium operates as a separate external entity that communicates with the browser using the WebDriver protocol.
      • It doesn't have direct access to the DOM and communicates with the browser through the WebDriver API.
      • Selenium can test multiple tabs or windows and supports cross-browser testing.
      • Selenium uses a client-server architecture with WebDriver acting as the server.
      • Selenium supports multiple programming languages, including Java, Python, C#, Ruby, and JavaScript, allowing you to choose the language you're most comfortable with.
      • Selenium supports a wide range of browsers, including Chrome, Firefox, Edge, Safari, and others
      • Selenium often requires explicit waits to handle synchronization issues.
      • Selenium provides debugging through standard development tools and logs.

  • Folder structure of Cypress project

    • fixtures: 
      • This folder contains fixture files used to store test data or mock responses. Fixture files can be in various formats like JSON, XML, or plain text.
    • e2e: 
      • Test scripts are placed in this folder. Each .js file in this folder represents a test suite or a collection of related test cases. You can organize your tests into subfolders for better organization.
    • support: 
      • The commands.js file in this folder is used for defining custom commands that you can use in your test scripts. The index.js file can contain additional support configurations and setup code.The e2e.js file in this folder is used for extending Cypress's functionality. You can define custom commands, modify browser behavior, or use third-party plugins here
    • screenshots:
      • Screenshots taken during test failures are stored in this folder. They can be helpful for diagnosing issues.
    • videos: 
      • If you enable video recording of test runs, the video files are stored here.
    • downloads: 
      • If your tests involve file downloads, the downloaded files are stored in this folder.
    • reports: 
      • This folder can be used to store any test reports or logs generated during test runs, such as HTML reports generated by a reporting library like Mochawesome.
    • cypress.config.js: 
      • This is the configuration file for Cypress. It allows you to specify settings like the base URL, browser preferences, and file paths.

Subject-specific questions

  • How to get the first and last child elements?

    • cy.get('.list-item').last().click(
    • cy.get('.list-item').first().click(); 

  • Difference between cy.log() and console.log() ?

    • Purpose:

       `cy.log()`: This is a Cypress command used for logging information specifically within Cypress test scripts. It is meant for logging messages that are relevant to your test cases and can be viewed in the Cypress Test Runner's Command Log. It helps you debug and understand the flow of your test scripts.


      - `console.log()`: This is a standard JavaScript function used for logging information in the browser's developer console. It is primarily used for debugging JavaScript code in your application. It's not part of Cypress itself but is a core feature of the browser's DevTools.


      2. Output Location:


      - `cy.log()`: Logs generated by `cy.log()` are displayed in the Cypress Test Runner's Command Log, making them easily accessible while running and debugging your tests within the Cypress environment.


      - `console.log()`: Logs generated by `console.log()` are displayed in the browser's developer console. These logs are typically used for debugging your application code and are not directly visible in the Cypress Test Runner.


      3. Timing:


      - `cy.log()`: Logs generated by `cy.log()` are synchronized with the Cypress test runner and will appear in the order they are executed within your test script. They are part of your test's execution timeline.


      - `console.log()`: Logs generated by `console.log()` are asynchronous, meaning they may not appear in real-time order in the console, especially when dealing with asynchronous code. This can make it challenging to correlate them with specific test steps.

  • How to run only specific scripts in the command line?

    • npx cypress run --spec "cypress/e2e/2-advanced-examples/actions.cy.js"

  • How to write files in Cypress?

    • cy.writeFile('path/to/message.txt', 'Hello World')

  • How to read files from Cypress?

    • cy.readFile('path/to/message.txt').then((text) => {
      expect(text).to.equal('Hello World') // true
      })

  • How to install a particular version of Cypress?

    • npm install cypress@versionnumber

  • How to use scrolling in Cypress?

    • cy.get('#element-to-scroll').scrollIntoView();
    • cy.scrollTo('top');
    • cy.scrollTo('bottom');
    • cy.scrollTo(0, 500);

How to handle alerts in Cypress

 Alerts, in the context of web development and user interfaces, are pop-up dialog boxes that display important information or notifications to users. They are commonly used to convey messages, warnings, errors, or requests for user input. Here's a brief description of different types of alerts:

  • Alerts: Alerts are simple pop-up boxes that display a message to the user. They typically have an "OK" button to acknowledge and dismiss the message. They are often used to convey information or provide notifications.
it('Alerts', () => {
cy.visit('http://the-internet.herokuapp.com/javascript_alerts')
cy.get('button[onclick="jsAlert()"]').click()
cy.on('window:alert', (a) => {
expect(a).to.contains('JS')
})
cy.get('#result').should('have.text','You successfully clicked an alert')
})
  • Confirm Dialogs: Confirm dialogs are similar to alerts but include two buttons, usually "OK" and "Cancel." They are used to prompt the user for confirmation or to make a decision, such as confirming the deletion of an item.
it('confirm alert', () => {
cy.visit('http://the-internet.herokuapp.com/javascript_alerts')
cy.get('button[onclick="jsConfirm()"]').click()
cy.on('window:confirm',(b) => {
expect(b).contains('JS')
})
cy.on('window:confirm', () => true);
cy.get('#result').should('have.text' ,'You clicked: Ok')
  • Prompt Dialogs: Prompt dialogs are like confirm dialogs but also include a text input field. They ask the user for input, such as their name or a value, and often have "OK" and "Cancel" buttons. Prompt dialogs are used when user input is required.

Cypress Important Points

 Cypress offers developers a powerful and user-friendly testing framework that simplifies test automation and enhances the reliability of web applications


How to do drag and drop in cypress

cy.get('#id').trigger('mousedown' , {which : 1 }) -  click on the middle of the icon
cy.get('data-set').trigger('mousemove')
cy.get('.class').trigger('mouseup')

How to verify Title

    cy.title().should('include', 'test automation')
    • This means that it doesn't require the full text of the title. Only part of it is enough 

Multiple assertions

       cy.get('#id').should('contain','abc').and('be.visible')

contain and contains
Contain : Method is used to assert that a DOM element contains specific text content

cy.get('#id').should('contain', 'Submit')

Contains : Method is used to select and interact with elements that contain specific text content

 cy.contains('Submit').click()