Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

Cypress Assignment A

Q1. Selectors:
- How do you select an element using Cypress, and what are the
different types of selectors available?
- Explain the differences between cy.get(), cy.contains(), and cy.find()
when selecting elements in Cypress.
- What is the significance of chaining in Cypress, and how can it be
applied when working with selectors?
- How do you handle selecting multiple elements with Cypress, and
what methods are available for such scenarios?

Q2. Assertions:
- What role do assertions play in Cypress, and why are they essential in
test automation?
- Explain the usage of common Cypress assertions like should (), expect
(), and assert ().
- How would you handle asynchronous assertions in Cypress, especially
when waiting for an element to meet a certain condition?

Q3. cy.url ():


- How do you retrieve the current URL in a Cypress test using cy.url ()?
- Explain a scenario where checking the URL using cy.url () is crucial in a
Cypress test.
- How can you assert the current URL matches a specific pattern or value
in Cypress?

Q4. Intercept:
- What is request interception in Cypress, and how can it be beneficial in
testing?
- Explain the steps to intercept and stub a network request in Cypress.
- How would you use request interception to simulate different
responses, such as success or error, during testing?
Cypress Assignment A
QUESTION 1 (SELECTORS)

Que. 1. a) How do you select an element using Cypress, and what are the
different types of selectors available?

In Cypress, selecting elements from the DOM (Document Object Model) is


crucial for testing. Cypress provides a variety of selectors to target elements
effectively. Here's how you can select elements using Cypress and the
different types of selectors available:
By CSS Selector
This is the most common way to select elements using Cypress.
EX:-
cy.get('button') // selects all <button> elements
cy.get('.my-class') // selects elements with class="my-class"
cy.get('#my-id') // selects element with id="my-id"
By XPath
XPath allows more complex selection based on the element's position,
attributes, etc.
EX:-
cy.xpath('//button[text()="Submit"]') // selects button with text "Submit"

By Data Attribute
This is useful when elements don't have suitable classes or IDs.
EX:-
cy.get('[data-cy="submit-button"]') // selects element with data-
cy="submit-button"

By Text
Select elements based on their text content.
EX
cy.contains('Submit') // selects elements containing the text "Submit".
By Test ID

Some prefer to add test-specific IDs to elements for easier testing.


EX
cy.getTestId('submit-button') // selects element with test ID "submit-button"
By Accessibility Attributes
Cypress also supports selecting elements based on their accessibility
attributes.
EX
cy.get('button').contains('Submit').as('submitButton') // using `contains` and
aliasing
cy.get('@submitButton').click() // referencing the button by its text

Que 1. b. Explain the differences between cy.get(), cy.contains(), and cy.find()


when selecting elements in Cypress.

Selector
Method Description Usage Example
Selects elements based on CSS selector,
cy.get() DOM element, or alias. cy.get('.btn')
Finds elements containing specified text
content. Can be combined with a selector
cy.contains() to narrow down the search. cy.contains('button', 'Submit')
Finds descendant elements within the
cy.find() currently selected element(s). cy.get('.parent').find('.child')

cy.get(): This is the most general selector in Cypress. It selects elements


based on CSS selectors, DOM elements, or aliases. It can be used to select
multiple elements matching the given selector.

cy.get(): This is the most general selector in Cypress. It selects elements


based on CSS selectors, DOM elements, or aliases. It can be used to select
multiple elements matching the given selector.

cy.find(): This method is used to find descendant elements within the


currently selected element(s). It's useful when you want to search for
elements within a specific parent element already selected using cy.get(). It
helps in narrowing down the scope of the search to descendants of the
selected elements.
// cy.get() example: Selects all elements with the class 'btn'
cy.get('.btn');

// cy.contains() example: Finds a button element containing the text 'Submit'


cy.contains('button', 'Submit');

// cy.find() example: Finds elements with the class 'child' within elements with
the class 'parent'
cy.get('.parent').find('.child');

In summary, cy.get() is used for general element selection, cy.contains() is


used for finding elements based on their text content, and cy.find() is
used for finding descendant elements within a selected element.

Question no 1 . c )

What is the significance of chaining in Cypress, and how can it be applied


when working with selectors?

Answer

Chaining in Cypress is fundamental to its syntax and plays a crucial role in


creating concise, readable, and powerful test scripts. It allows you to string
together multiple commands, each acting on the result of the previous one.
This chaining approach enables a fluent and expressive style of writing
tests.

1. Sequential Actions:
Chaining allows you to perform a series of actions on the same elements
without repetitive selection.

For example:

'Hello') // Check if the value is 'Hello'


.clear() // Clear the input field
.should('have.value', ''); // Check if the input is empty
cy.get('.input')
.type('Hello') // Type into the input field
.should('have.value'
2. Readable Assertions:
Chaining assertion commands after selectors makes test assertions
highly readable. It ensures that assertions are applied to the correct
elements.
For example:
cy.get('.message')
.should('be.visible') // Check if the message element is visible
.should('contain', 'Success'); // Check if the message contains 'Success'

3. Scoped Selections:
Chaining allows you to scope subsequent commands to specific
elements, reducing the scope of search and making tests more
resilient.
For example:
cy.get('.container')
.find('.item') // Find items within the container
.should('have.length', 3); // Check if there are three items

4. DOM Traversal:
Chaining with traversal commands like .find() or .children() allows
you to navigate through the DOM hierarchy and interact with nested
elements.
For example:
In summary, chaining in Cypress streamlines test script writing by
providing a fluent interface for selecting elements, performing
actions, and making assertions. It enhances code readability, reduces
redundancy, and facilitates efficient interaction with elements on the
web page.
Question no 1. d)

How do you handle selecting multiple elements with Cypress,


and what methods are available for such scenarios?

Handling multiple elements in Cypress involves selecting a group of


elements that match a specific selector or criteria. Cypress provides
several methods for selecting multiple elements:

cy.get(): The cy.get() method is the primary way to select elements


in Cypress. It can select multiple elements using CSS selectors, DOM
elements, or aliases.
For example:
cy.get('.list-item'); // Selects all elements with the class 'list-
item'
cy.contains(): While primarily used for finding elements containing
specific text content, cy.contains() can also be used to select
multiple elements. By combining it with a CSS selector as the first
argument, you can narrow down the search scope.
For example:
cy.contains('.container', 'Button'); // Selects all elements with
class 'container' containing the text 'Button'
Parent-Child Relationships: You can use parent-child relationships
to select multiple elements within a specific parent element. This can
be achieved using chaining, where you first select the parent element
and then use traversal methods like .find() or .children() to select
its children.
For example:
cy.get('.parent').find('.child'); // Selects all elements with class
'child' within elements with class 'parent'
Iterating Over Elements: Cypress also allows you to iterate over
multiple elements using commands like .each(). This method iterates
over each element in the selection and executes a callback function.
For example:
cy.get('.list-item').each(($item) => {
// Perform actions/assertions on each item
});
Filtering: Cypress provides methods like .filter() and .eq() to
further refine selections. .filter() allows you to select elements that
match specific criteria, while .eq() selects elements at a specified
index within the selection.
For example:
cy.get('.list-item').filter('.active'); // Selects active items within
the list
cy.get('.list-item').eq(0); // Selects the first item in the list

………………………………………………………………………………………………

Assertions:
Question no 2 => a.

- What role do assertions play in Cypress, and why are they essential
in test automation?

Verification of Expected Behavior: Assertions allow you to verify that


certain conditions or behaviors exist within your application. This is critical
in ensuring that your application functions as expected, according to the
requirements and specifications.
Error Detection: Assertions help in detecting errors or unexpected
behavior in your application. They provide a mechanism to automatically
verify that the elements, states, or interactions in your application meet the
expected criteria. If an assertion fails during test execution, it indicates a
deviation from the expected behavior, enabling you to identify and
diagnose issues promptly.
Feedback Mechanism: Assertions serve as a feedback mechanism during
test execution. They provide feedback on the state of your application,
indicating whether it conforms to the expected behavior or not. This
feedback is invaluable for developers and testers to understand the quality
and reliability of the application under test.
Documentation of Behavior: Assertions act as documentation of the
behavior and requirements of your application. By writing assertions that
reflect the expected behavior of your application, you create executable
documentation that serves as a reference for developers, testers, and other
stakeholders.
Regression Testing: Assertions are instrumental in regression testing,
where changes to the codebase can potentially introduce new bugs or
regressions. By asserting key aspects of your application's behavior, you can
ensure that existing functionality remains intact across different versions or
iterations of your application.
Continuous Integration and Deployment (CI/CD): Assertions are integral
to automated testing in CI/CD pipelines. They enable you to automatically
validate the correctness of your application at various stages of the
development lifecycle, from local development environments to production
deployments. Assertions help maintain confidence in the quality of your
application as it progresses through different stages of the CI/CD pipeline.

Overall, assertions play a critical role in test automation by providing


a mechanism to verify expected behavior, detect errors, provide feedback,
document behavior, support regression testing, and facilitate automated
testing in CI/CD pipelines. They are essential for building robust, reliable,
and maintainable test suites that ensure the quality and integrity of your
application.

Question no 2 => b.

- Explain the usage of common Cypress assertions like should (),


expect (), and assert ().

Certainly! Cypress provides multiple ways to perform assertions, including the


commonly used methods `should()`, `expect()`, and `assert()`.

1. **should():**
- The `should()` method is the most commonly used assertion method in
Cypress. It is applied directly to a Cypress command and allows you to chain
assertions to verify the state of elements or the application.
- It is used with commands like `cy.get()`, `cy.contains()`, and others to assert
conditions on the selected elements or the results of actions.
- Example usage:
```javascript
cy.get('.submit-button').should('be.visible'); // Asserts that the submit
button is visible
cy.get('.message').should('contain.text', 'Success'); // Asserts that a message
contains the text 'Success'
```

2. **expect():**
- The `expect()` method comes from the Chai assertion library, which Cypress
utilizes. It is typically used for standalone assertions outside of the Cypress
command chain.
- It allows you to make assertions on specific values or expressions.
- Example usage:
```javascript
expect(true).to.be.true; // Asserts that the value is true
expect(5).to.equal(5); // Asserts that the value is equal to 5
```

3. **assert():**
- The `assert()` method comes from the Chai assertion library as well, similar
to `expect()`. It is also used for standalone assertions.
- It provides a different syntax compared to `expect()` but serves the same
purpose.
- Example usage:
```javascript
assert.isTrue(true); // Asserts that the value is true
assert.strictEqual(5, 5); // Asserts that the values are strictly equal
```

In summary, `should()` is primarily used within the Cypress command chain to


assert conditions on elements or application state. `expect()` and `assert()` are
often used for standalone assertions outside of the Cypress command chain,
providing flexibility in assertion syntax. All three methods serve the purpose of
verifying expected behaviour and ensuring the correctness of your tests.
Question no 2 => c.
How would you handle asynchronous assertions in Cypress,
especially when waiting for an element to meet a certain condition?

Handling asynchronous assertions in Cypress, especially when waiting for an


element to meet a certain condition, typically involves using Cypress's built-in
retry mechanism along with chaining assertions using `should()` or `wait()`
commands. Here's how you can handle such scenarios:

1. **Chaining Assertions with should():**


You can chain assertions with the `should()` command, which automatically
retries the assertion until it passes or times out. This is useful for waiting for an
element to meet a certain condition.
```javascript
// Example: Waiting for an element to be visible
cy.get('.my-element').should('be.visible');
```
2. **Using Custom Assertions:**
If the built-in assertions provided by Cypress are not sufficient for your needs,
you can create custom assertions using Cypress commands like `cy.wrap()`. This
allows you to define your own assertion logic and handle asynchronous
conditions.
```javascript
// Example: Custom assertion for checking if an element contains specific text
after a certain time
cy.get('.my-element')
.should($el => {
return new Cypress.Promise(resolve => {
const checkText = () => {
if ($el.text() === 'Expected Text') {
resolve(true);
} else {
setTimeout(checkText, 1000); // Retry after 1 second
}
};
checkText();
});
});
```
3. **Using wait():**
Cypress provides the `wait()` command, which allows you to wait for a
specific condition to be true before proceeding with the test. You can use it in
combination with assertions to wait for an element to meet a certain condition.

// Example: Waiting for an element to contain specific text


cy.get('.my-element').wait(() => {
return cy.get('.my-element').then($el => {
return $el.text() === 'Expected Text';
});
});
```

4. **Handling Timeout:**
It's important to set appropriate timeouts for your assertions to prevent tests
from running indefinitely. You can set a timeout using the `timeout()` command
or by passing a timeout option to the `should()` or `wait()` commands.

// Example: Setting a timeout for assertion


cy.get('.my-element').should('be.visible', { timeout: 5000 }); // Timeout after 5
seconds
```
By using these techniques, you can effectively handle asynchronous assertions
in Cypress, ensuring that your tests wait for elements to meet specific
conditions before proceeding, thereby improving the reliability and stability of
your tests.

Question no 3 cy.url ():


Question no 3 => a. How do you retrieve the current URL in a
Cypress test using cy.url ()?

Answer:-

In Cypress, you can retrieve the current URL using the `cy.url()`
command. This command returns a promise that resolves with the
current URL. Here's how you can use it in a Cypress test:

it('should retrieve the current URL', () => {


cy.visit('https://example.com');
cy.url().should('eq', 'https://example.com');
});
```
This test visits `https://example.com` and then asserts that the
current URL is equal to `https://example.com`. If the URL is different,
the test will fail.

Question no 3 => b.

Explain a scenario where checking the URL using cy.url () is crucial in a


Cypress test.
Answer:-
Checking the URL using `cy.url()` is crucial in various scenarios in
Cypress tests, especially when dealing with web applications that
involve navigation, dynamic URLs, or deep linking. Here's a scenario
where checking the URL is crucial:

Scenario: User navigates to a specific page after an action


- **Scenario Description**: Imagine you have a web application with
a multi-step form. After the user fills out the first part of the form
and clicks "Next," they should be redirected to a different URL or
page where they can continue the form.
- **Test Objective**: You want to ensure that after the user clicks
"Next," they are redirected to the correct URL.
- **Test Steps**:
1. Visit the initial page of the form.
2. Fill out the required fields.
3. Click the "Next" button.
4. Check that the URL has changed to the expected URL for the next
step/page.

Here's an example test using Cypress:

it('should navigate to the next step after clicking "Next"', () => {


// Visit the initial page of the form
cy.visit('/form');

// Fill out the required fields


cy.get('#name').type('John Doe');
cy.get('#email').type('john@example.com');

// Click the "Next" button


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

// Check that the URL has changed to the expected URL for the next
step/page
cy.url().should('include', '/form/step2');
});

In this scenario, checking the URL using `cy.url()` ensures that the
navigation after clicking "Next" is working as expected. If there's an
issue with the routing or redirection, this test will fail, providing
valuable feedback to the developer. Additionally, it helps to ensure
that the application behaves correctly, especially in cases where deep
linking or bookmarking specific steps/pages is involved.

Question no 3 => c.
- How can you assert the current URL matches a specific pattern or value in
Cypress?

Answer

In Cypress, you can assert that the current URL matches a specific pattern or
value using various Cypress commands, such as `cy.url()`, `.should()`, and
regular expressions. Here's how you can do it:

1. **Using `.should()` with a string comparison**:

cy.url().should('eq', 'https://example.com/page');

This assertion checks that the current URL is exactly


`https://example.com/page`.

2. **Using `.should()` with a regular expression**:

cy.url().should('match', /https:\/\/example\.com\/\w+/);

This assertion checks that the current URL matches the regular expression
pattern `/https:\/\/example\.com\/\w+/`. This pattern matches any URL
starting with `https://example.com/` followed by any alphanumeric characters.

3. **Using custom assertions**:

cy.url().then(url => {
expect(url).to.match(/https:\/\/example\.com\/\w+/);
});

This approach allows for more customization in assertions. You can use the
`expect()` function with Chai assertions and regular expressions to match the
URL pattern.

Choose the method that best fits your testing needs and the level of specificity
required for your assertions.

Question no 4 Intercept:
Question 4.1
What is request interception in Cypress, and how can it be beneficial in
testing?
Answer
Request interception in Cypress refers to the capability of intercepting and
modifying HTTP requests made by the application under test. Cypress allows
you to intercept and manipulate both incoming and outgoing requests,
enabling you to control the behavior of the application during testing.

Here's how request interception works in Cypress and its benefits in testing:

1. **Intercepting Outgoing Requests**:


- Cypress allows you to intercept outgoing HTTP requests before they are sent
to the server.
- You can modify request headers, payloads, or even mock responses to
simulate different server behaviors.
- This is beneficial for testing scenarios where you need to simulate various
server responses, test error handling, or mock responses for endpoints that are
not yet implemented.

2. **Intercepting Incoming Responses**:


- Cypress also enables you to intercept incoming HTTP responses before they
are processed by the application.
- You can modify response payloads or headers, allowing you to simulate
different server responses and test how the application handles them.
- This is useful for testing error handling, edge cases, or scenarios where you
need to simulate specific server conditions.

3. **Network Traffic Control**:


- With request interception, you have full control over the network traffic
during testing.
- You can simulate different network conditions, such as slow connections or
network failures, to test how the application behaves under adverse
conditions.
- This helps ensure that the application is resilient and provides a good user
experience even under challenging network conditions.

4. **Integration Testing**:
- Request interception is invaluable for integration testing, allowing you to
test the interaction between different parts of the application and external
services.
- You can mock responses from external APIs or services, ensuring that
integration points are tested thoroughly without relying on external
dependencies.

Overall, request interception in Cypress provides powerful capabilities for


testing HTTP interactions, enabling you to simulate various scenarios and
ensure the robustness and reliability of your web applications.

Question 4.2
Explain the steps to intercept and stub a network request in Cypress.
Answer

Intercepting and stubbing network requests in Cypress involves several steps.


Below are the general steps to intercept and stub a network request:

1. **Install Cypress**:
If you haven't already installed Cypress, you can do so using npm or yarn:
npm install cypress --save-dev
or
yarn add cypress --dev

2. **Write a Cypress Test**:


Create a Cypress test file (e.g., `example.spec.js`) where you will intercept and
stub the network request.

3. **Intercept the Network Request**:


Use the `cy.intercept()` command to intercept the network request. You can
specify the URL to intercept, the HTTP method, and optionally provide a
response or manipulate the intercepted request.

cy.intercept('GET', '/api/data', { fixture:


'example_response.json' }).as('getData');

In this example, we intercept a GET request to `/api/data` and provide a


response from a fixture file named `example_response.json`.
4. **Visit the Page or Trigger the Request**:
Navigate to the page or trigger the action that sends the network request you
intercepted.
cy.visit('/page');

5. **Wait for the Request to Complete**:


If necessary, wait for the intercepted request to complete using `cy.wait()`.
cy.wait('@getData');

This ensures that the test waits for the intercepted request to finish before
proceeding.

6. **Assertion (Optional)**:
Perform any assertions on the intercepted request or its response. This step
depends on the specific behavior you want to test.
cy.get('@getData').should('have.property', 'response');

7. **Run the Test**:


Run your Cypress test using the Cypress Test Runner or CLI.
npx cypress run --spec 'cypress/integration/example.spec.js'

By following these steps, you can intercept and stub network requests in
Cypress tests, enabling you to control the behavior of your application during
testing and simulate various scenarios.

Question 4.3

How would you use request interception to simulate different responses,


such as success or error, during testing?

Answer

To simulate different responses, such as success or error, during


testing using request interception in Cypress, you can intercept the
network requests and provide custom responses accordingly. Here's a
step-by-step guide on how to achieve this:

1. **Intercept the Network Request**:


Use the `cy.intercept()` command to intercept the network request.
Specify the URL, HTTP method, and optionally provide a response or
manipulate the intercepted request.

2. **Provide Different Responses**:


Depending on the scenario you want to simulate, provide different
responses for the intercepted request. You can simulate a successful
response, an error response, or any other relevant scenario.

3. **Perform Assertions** (Optional):


After intercepting the request and receiving the response, you can
perform assertions to verify that the application behaves as expected
based on the simulated response.

Here's an example demonstrating how to simulate different


responses using request interception in Cypress:

describe('Simulating Different Responses', () => {


it('should handle successful response', () => {
cy.intercept('GET', '/api/data', { statusCode: 200, body: { message:
'Success' } }).as('successRequest');
cy.visit('/page');

cy.wait('@successRequest').then(interception => {
expect(interception.response.statusCode).to.eq(200);
expect(interception.response.body.message).to.eq('Success');
// Add more assertions as needed
});
});

it('should handle error response', () => {


cy.intercept('GET', '/api/data/error', { statusCode: 500, body:
{ message: 'Error' } }).as('errorRequest');

cy.visit('/error-page');
cy.wait('@errorRequest').then(interception => {
expect(interception.response.statusCode).to.eq(500);
expect(interception.response.body.message).to.eq('Error');
// Add more assertions as needed
});
});
});

In this example:
- We intercept requests to `/api/data` and `/api/data/error` URLs.
- For the `/api/data` endpoint, we provide a successful response with
status code 200 and a message.
- For the `/api/data/error` endpoint, we provide an error response
with status code 500 and a message.
- In the test cases, we visit different pages triggering these requests,
wait for the interception to complete, and perform assertions on the
intercepted responses.

By simulating different responses using request interception, you can


thoroughly test how your application handles various scenarios, such
as success, error, or other specific conditions.

You might also like