What is the best way to choose the right value based on parameters?

I am currently working on a solution using protractor where I have several options to consider. Specifically, I need to test timeslots between 1600 and 1900, along with an else statement.

For instance, if the 1600 timeslot is selected, then the code should work accordingly for that element and so forth.

When executing the code, it follows this syntax:

npm run e2e.js --params.tiemslot.t1600

Alternatively, it can also be t1900 or no parameters at all.

The test cases are structured as follows:

const utils = require("../utils/utils");
const ServicesPage = require("../objects/servicesPage.obj");

describe("Services page", function () {
    servicesPage = new ServicesPage();

    if (browser.params.timeslot.t1600) {
        it("Should have truck and select the 1600 timeslot delivery",
            async function () {
                const nextStep = servicesPage.getForm().buttons.nextStep;

                await servicesPage.truckLateDelivery();

                await utils.elementToBeClickable(nextStep);
                await utils.click(nextStep);
            })
    }
    else if (browser.params.timeslot.t1900) {
        it("Should have truck and select the 1900 delivery",
            async function () {
                const nextStep = servicesPage.getForm().buttons.nextStep;

                await servicesPage.truckLateDelivery();

                await utils.elementToBeClickable(nextStep);
                await utils.click(nextStep);
            })
    }
    else {
        it("Should have truck and choose the latest delivery",
            async function () {
                const nextStep = servicesPage.getForm().buttons.nextStep;

                await servicesPage.chooseLatestDelivery();

                await utils.elementToBeClickable(nextStep);
                await utils.click(nextStep);
            })
    }
});

My object script looks like this:

const utils = require("../utils/utils");
const servicesPage = require("../specs/servicesPage.specs");

module.exports = class DetailsPage {
    constructor() {
        const _buttons = {
            nextStep: servicesPage.nextStepButton,
            lateDelivery: servicesPage.lateDeliveryCheckbox,
            truck: servicesPage.truckButton,
            timeSlotAll: servicesPage.timeslotAll,
            timeSlot1600: servicesPage.timeSlot1600,
            timeSlot1900: servicesPage.timeSlot1900,
        };

        this.getFormButtons = function () {
            return _buttons;
        };
    }

    getForm() {
        return {
            buttons: this.getFormButtons()
        };
    }

    async truckLateDelivery() {
        const truckButton = this.getForm().buttons.truck;
        const lateDelivery = this.getForm().buttons.lateDelivery;
        const timeslot = this.getForm().buttons.timeSlot1600;

        //Choose Truck
        await utils.elementToBeClickable(truckButton);
        await utils.click(truckButton);

        //Click Late Delivery
        await utils.elementToBeClickable(timeslot);
        await utils.click(timeslot);

        //Click late hour checkbox
        await utils.elementToBeClickable(lateDelivery);
        await utils.click(lateDelivery);
    }

    async chooseLatestDelivery() {

        const truckButton = this.getForm().buttons.truck;
        const lateDelivery = this.getForm().buttons.lateDelivery;
        const timeSlots = this.getForm().buttons.timeSlotAll;

        //Choose Truck
        await utils.elementToBeClickable(truckButton);
        await utils.click(truckButton);

        //Check if timeslots are available
        await utils.presenceOf(timeSlots);

        const countElement = await timeSlots.count();
        console.log(`Found ${countElement} timeslots buttons`);

        //Choose last timeslot
        await utils.elementToBeClickable(timeSlots.last());
        await utils.click(timeSlots.last());

        //Click on checkbox
        await utils.elementToBeClickable(lateDelivery);
        await utils.click(lateDelivery);
    }
};

I am facing a challenge in determining how to make the async truckLateDelivery() function aware of whether it should run t1600 or t1900 based on the command,

npm run e2e.js --params.tiemslot.t1600
or
npm run e2e.js --params.tiemslot.t1900
. How can I achieve this given the setup with the function _buttons containing the necessary elements and the truckLateDelivery() function handling the tests?

Any suggestions on how to instruct the test case to correctly choose between t1600 and t1900 based on the commands provided would be greatly appreciated.

Answer №1

To efficiently handle this task, it is recommended to provide a parameter to the truckLateDelivery() function and include an if statement inside it. Here's an example:

    async truckLateDelivery(timeslot) {
        const truckButton = this.getForm().buttons.truck;
        const lateDelivery = this.getForm().buttons.lateDelivery;
        const selectedTimeSlot = this.getForm().buttons.timeSlot1600;

        //Choose Truck
        await utils.elementToBeClickable(truckButton);
        await utils.click(truckButton);

        if(selectedTimeSlot === 1600)
        {
          //Click Late Delivery
          await utils.elementToBeClickable(selectedTimeSlot);
          await utils.click(selectedTimeSlot);
        }
        else
        {
          //Click late hour checkbox
          await utils.elementToBeClickable(lateDelivery);
          await utils.click(lateDelivery);
        } 
    }

When calling truckLateDelivery(), use

await servicesPage.truckLateDelivery(1600);
for late delivery
await servicesPage.truckLateDelivery(1900);
for 1-hour late delivery

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

Commitment failing to deliver the information

I am currently attempting to retrieve data based on a specific ObjectId using promises. The function is successfully fetching the data from the database, but it is failing to return the result as expected. Below is the code snippet: getScreenDetails = fun ...

What is the best method for incorporating jQuery code into a separate file within a WordPress theme?

I'm fairly new to working with Javascript/jQuery, so please be patient with me. Currently, I'm in the process of creating a custom WordPress theme where I've been using jQuery to modify the main navigation menu generated in my header file ( ...

What is the best way to link CSS files from libraries that are downloaded using npm?

For instance, let's say I installed a package: npm install --save package and it gets saved in ./node_modules/package/ Inside that folder, there might be a directory named styles and within that directory, you could find style.css. How can I link ...

Delete an item from an array based on its index within the props

I am attempting to remove a specific value by its index in the props array that was passed from another component. const updatedData = [...this.props.data].splice([...this.props.data].indexOf(oldData), 1); const {tableData, ...application} = oldData; this ...

Next JS Event Listener Failing to Detect Scroll Events

Currently, I am attempting to change the state and display a shadow in the navigation bar when the user scrolls, but for some reason it is not detecting the event. I am working with nextJS 13 and tailwind css. const [shadow, setShadow] = useState(false) ...

The API response was blocked due to the CORS header "Access-control-allow-origin."

I have an index.html file that is used for making HTML and Ajax calls. When I run the file through localhost, the API works perfectly. However, if I directly open the index.html file in Google Chrome or Mozilla Firefox, I encounter a CORS (Cross-Origin Re ...

Creating a React component that allows for pagination using data fetched from a

I have a Spring Boot endpoint that retrieves and lists items from a database: @RequestMapping(method = RequestMethod.GET, value = "/task", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> processTask(@Valid TaskSearchP ...

Update Table Row Background Color in Separate Table by Clicking Button Using JQuery

Two tables are involved in this scenario - one that receives dynamically added rows, and another that stores the data to be included. The illustration above displays these tables. Upon clicking the Edit button, the information from the selected row in Tab ...

In React's contextApi, the this.context object is constantly devoid of any values

sample.js export default class SampleComponent extends React.Component { static contextType= AppProvider; componentDidMount() { console.log('sample',this.context); } render() { return ( <AppConsumer> ...

Verify whether the element has been clicked prior to deletion

Here is the jquery code I'm working with: $(document).on('focusout', '#element_a', function(e){ $('#element_b').remove(); }); $(document).on('click', '#element_b', function(e){ // additional ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

Modifying the CSS class of an element does not produce the desired effect after altering its styles using JavaScript

html: <input id="myinput" class="cinput" type="image" src="http://www.foodwater.org.au/images/triple-spiral-3-small-button.jpg"/> <br><br><br><br> <button id="s">set to visible class</button> <button id="h"> ...

Guide to accessing a nested and potentially optional object property with a default value and specifying its data type

Just a simple query here... my goal is to extract data.user.roles, but there's a possibility that data may be empty. In such cases, I want an empty array as the output. Additionally, I need to specify the type of user - which in this instance is any. ...

When attempting to execute the 'npm start' command, an error was encountered stating "start" script is

Encountering an issue when running "npm start." Other users have addressed similar problems by adjusting the package.json file, so I made modifications on mine: "scripts": { "start": "node app.js" }, However, t ...

An unexpected error has occurred: Uncaught promise rejection with the following message: Assertion error detected - The type provided is not a ComponentType and does not contain the 'ɵcmp' property

I encountered an issue in my Angular app where a link was directing to an external URL. When clicking on that link, I received the following error message in the console: ERROR Error: Uncaught (in promise): Error: ASSERTION ERROR: Type passed in is not Co ...

What is the reason for NextJS/React showing the message "You probably didn't export your component from the file where it was declared"?

What's the Issue The error code I am encountering Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the ...

<Select> Placeholder customization

For my react project, I am utilizing material-Ui and I am looking to have a placeholder that stands out by having grey text instead of black when compared to the selected item. <Select name="answer" value={values.answer} onChange={handleChange} onBlur= ...

Error: Unable to find the specified "location.ejs" view in the views directory

I am encountering the following error - Error: Failed to find view "location.ejs" in views folder "e:\NodeJs_Project\geolocationProject\views" at Function.render Your help in resolving this issue would be greatly appreciated. server.js ...

javascript: restrict the quantity of products

As a beginner in javascript, I am currently working on creating a simple RSS reader. However, I am facing a challenge in limiting the number of feeds to 5 items, especially since the target site may have 100 or more feeds. Here's the code snippet I&ap ...

Retrieve the ID of the nearest div without it being executed twice

I am currently working on implementing a close button using 'onclick' functionality. The goal is to hide the parent ID element when the user clicks the button, as shown below. function displayNone() { var id= $('.btnClose').closest ...