Guide to implementing if else statements with Protractor

I am facing some unusual situations and I'm not quite sure how to address them.

As a newcomer to testing, I've been tasked with testing a website's cart function for proper functionality.

The challenge arises when we add a certain number of products to the cart and run a stock check. If there is a conflict in stock availability, we must resolve it before proceeding; otherwise, we can continue as usual.

I have successfully created a function that resembles the following:

describe("Details page", function () {

    detailsPage = new DetailsPage();

    // Checking if the details page is accessible via the specified URL
    it(`Is defined by the URL: ${userData["url"]}${browser.baseUrl}`,
        async function () {
            await detailsPage.navigateDesktop();
        });

    // Verifying that the details page includes a form for user data input
    it("Has a form that can receive user data",
        async function() {
            await detailsPage.fillFormWithUserData();
            await utils.click(detailsPage.getForm().buttons.nextStep);
        });

    if (detailsPage.hasStockConflict()) {

        // Allowing users to resolve stock conflicts on the details page
        it('Enables resolution of stock conflicts', async function () {
            // Waiting for stock information to fully load
            await detailsPage.hasStockConflict();
            await detailsPage.clickAllRemoveButtons();
            await detailsPage.clickAllDecreaseButtons();
        });

        // Granting access to the next stage of purchasing once all conflicts are resolved
        it('Allows the user to proceed to the next stage of purchasing', async function () {
            const nextStepButton = detailsPage.getForm().buttons.nextStep;
            await utils.elementToBeClickable(nextStepButton);
            await utils.click(nextStepButton);
        });
    }
});

However, my main issue lies in the fact that I need to wait until I receive a response from the server. This could either be a stock conflict triggered by:

hasStockConflict() //checks if there is stockConflict message in DOM

Or redirection to a new page.

My question is, how can I create a functional solution that automatically checks for a stock conflict? If one is detected, the problem should be resolved; otherwise, we can bypass this step and move forward without interruption (leading us to the next page).

I have set a timeout of 1 minute. If no resolution is reached within that time frame, the test will fail.

In essence, I aim to handle stock conflicts as required or skip over them seamlessly. Any guidance on effective testing practices would also be greatly appreciated!

Answer №1

Expanding on the advice from Code-Apprentice, consider creating mock data to customize the responses you receive. It's important to have a variety of responses to simulate different scenarios without relying on if/else statements in your testing steps.
In this situation, test with items that are known to be in stock or create fictional in-stock and out-of-stock items for your database. Develop separate tests for each scenario and tailor them to your needs.

Hopefully this guidance proves helpful!

Answer №2

For effective testing, focus each test on a specific aspect without incorporating unnecessary if...else branching. Instead, create separate tests for each scenario with initialized data that aligns with the particular scenario.

There are two approaches to achieve this:

  1. Arrange data in a resource and retrieve the necessary data for the scenario under examination.

  2. Alternatively, simulate the resource behavior by generating mock data tailored to the scenario being evaluated.

Answer №3

It is widely acknowledged that following best practices can help avoid potential pitfalls in the future...

However, it's important to note that the best practice #1 is always subjective and dependent on factors such as company, product, and individual needs. So if you believe this approach suits your situation, go ahead with it

Reasons why your current setup may not be effective

In short, your code blocks are generated before the browser initialization. This could lead to your functions failing or returning undefined

Solution

That being said, it is crucial not to skip the it block; instead, ensure to encapsulate your logic within it like demonstrated below

        it('Addresses stock conflict resolution', async function () {
          if (detailsPage.hasStockConflict()) {
            // Ensure stock information is fully loaded
            await detailsPage.ensureStockLoaded();
            await detailsPage.clickAllRemoveButtons();
            await detailsPage.clickAllDecreaseButtons();

            const nextStepButton = detailsPage.getForm().buttons.nextStep;
            await utils.makeElementClickable(nextStepButton);
            await utils.click(nextStepButton);
          }
        });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to retrieve the HTML code for links

I am looking for a way to extract HTML links from a specific div without relying on regular expressions. Here is an example scenario: <div>Please review the links provided in the content. For instance, <a href="http://en.wikipedia.org/wiki/Apple ...

Discovering the smallest, largest, and average values across all properties in an array of objects

Given an array of objects with varying values, the task is to determine the minimum, maximum, and average of the properties in that array. For example, consider the following array: const array = [{ "a": "-0.06", "b": "0.25", "c": "-0.96", ...

Building interactive web forms with real-time validation using CodeIgniter

I'm looking for a way to use ajax (jquery library) to validate my forms. Specifically, I have a form that requires a minimum password length of 6 characters. Currently, I have implemented the validation rule as follows, $this->form_validation-> ...

"Exploring JSON data with jQuery: A guide to efficient search techniques

I have a local file containing JSON data which I successfully loaded using jQuery. My current task is to specifically find the pId with the value of "foo1". The JSON data { "1":{ "id": "one", "pId": "foo1", "cId": "bar1" }, "2":{ ...

Delay with Vue.js v-bind causing form submission to occur before the value is updated

Trying to update a hidden input with a value from a SweetAlert modal, but encountering issues. The following code isn't working as expected - the form submits, but the hidden field's value remains null. HTML: <input type="hidden" name="inpu ...

Bug in timezone calculation on Internet Explorer 11

I've spent hours researching the issue but haven't been able to find any effective workarounds or solutions. In our Angular 7+ application, we are using a timezone interceptor that is defined as follows: import { HttpInterceptor, HttpRequest, H ...

After completing the mapSeries operation, I aim to re-implement the function

How can I return queries (functions) after performing mapSeries? Any help is appreciated! async querys(querys) { const pool = await poolPromise; if (pool != null) { const transaction = new sql.Transaction(pool); ...

Res.redirect() function does not redirect the browser URL as expected when triggered by a request made through a frontend fetch() call

Encountering a new issue that is challenging me. In the backend, there is an API route that redirects the browser URL to /signin using res.redirect('/signin'). Upon this redirection, React Router triggers the rendering of a 'log back in&apos ...

Accessing Properties in React.js: A Guide

<Element id="1" onClick={this.runFunction(???)}/> When the onClick event is triggered, I want to execute a different function with the key value "1" as an argument. How can I make this happen? Thank you. ...

Enhance your browsing experience by inputting valuable information into the

I am looking to enhance a text box by adding values. The text box already has a default value of 10, and I want to create a button that will add new text boxes with a limit of 4. My goal is to continuously add values from text box 1 to text box 4. For exa ...

Arrange the child elements of a div to be displayed on top of one another in an HTML document

I am struggling with a div containing code .popupClass { width: 632px; height: 210px; position: absolute; bottom:0; margin-bottom: 60px; } <div class="popupClass"> <div style="margin-left: 90px; width: 184px; hei ...

Issue encountered while trying to define a global variable within a JavaScript Class

I'm currently working on setting up a page variable that can be utilized by my Scroller class for implementing infinite scrolling. It's crucial for this variable to have global scope, as it needs to retain its value outside of the ajax function. ...

Ways to transfer various data values from an Excel sheet to a single step in a Cucumber scenario

Trying to utilize the step "@when user enters the field value as 'something'" for 10 Scenarios, with each test case needing different values. However, steps cannot be repeated in the step definition. I have a utility using an Excel hashmap that ...

Is this example showcasing the use of JavaScript closures?

I have a JavaScript query that may be geared towards beginners: var countries = [ "Bangladesh", "Germany", "Pakistan"]; function checkExistence(arr, input) { for (var i = 0; i < arr.length; i++) { if (arr[i] != input) { a ...

BOOTSTRAP: changing the layout of panels in various sizes for mobile devices

I'm struggling with how to reorganize my panels on mobile devices. Each panel has a different size. Please refer to the attached screenshot for the page layout on large screens (col-lg): https://i.sstatic.net/xcqaT.png EDIT: The layout on large scre ...

Encountering an issue with the message "SyntaxError: Unexpected token < in django-jquery-file

I am currently working on implementing django-jquery-fileupload into my project. https://github.com/sigurdga/django-jquery-file-upload However, I encounter an "Error SyntaxError: Unexpected token < " when attempting to click the "start" upload button. ...

Changing the shape of a background using CSS when hovering

My Bootstrap navigation has a unique setup, as shown below. I've observed that many users tend to only interact with the headings and ignore the submenus where the actual products are located. To address this issue, I want to change the design of th ...

Searching for and replacing anchor tag links within a td element can be achieved using PHP

I am currently customizing my WordPress website and I need to update the URL (product link) of the "product-image" on the "cart" page. I have the following dynamic code: <td class="product-name" data-title="Product"> <a href=&q ...

executing functions that return a JSX component within the render method

In an effort to enhance readability, I am striving to condense the length of the render() method by utilizing class methods that contain isolated JSX elements. A snag arises when attempting to apply this technique to more than one JSX element. Despite en ...

Issues with executing basic unit test in Angular Js

THE ISSUE: In an attempt to create unit tests for my Angular application, I set up a basic test app and wrote a simple unit test. However, the test is not functioning as expected. APPLICATION CODE: var app = angular.module( 'myApp', [] ); app ...