Guide on sending a POST request with Protractor

Attempting to hit an endpoint with a POST request using Protractor has been quite challenging for me. I have tried various versions of the code, utilizing different HTTP clients like 'request' and exploring other options as well.

In addition to that, I am also using cucumber and chai-as-promise in my testing process. However, when running the cucumber test, the POST request does not seem to execute properly. The test simply moves on to the next step without displaying any errors in the console. Subsequently, checking with a REST client confirms that the POST request was not successful.

I am wondering if moving the post request into a separate function within a class and passing the appropriate variables would make a difference?

Below is the code snippet:


this.When(/^I test this$/, function (next) {
    var request = require('request');
    var options = {
        headers: {
            'id': 'AQ8WHWC',
            'sessionid': 'XnINW5KDQg=',
            'Accept': 'application/json',
            'Accept-Language': 'en-us',
            'random': 'BS3P5Q'
        },
        form: { "pay_load": [] }
    };
    request.post('http://myurl.com/endpoint/test/', options, callback);

    function callback(error, response, body) {
        if (!error && response.statusCode == 200) {
            var info = JSON.parse(body);
            console.log(info);
        }
    }
    browser.sleep(1).then(next)
});

Console output from running the cucumber test:

 Scenario: this is a cool test
# endpoint/test/testing.feature:7
Given I run this endpoint test
# endpoint/test/testing.feature:8
When I test this                                             
# endpoint/test/testing.feature:9
Then I see this                                    
# endpoint/test/testing.feature:10

1 scenario (1 passed)
3 steps (3 passed)
[launcher] chrome passed

Done, without errors.

Answer №1

The root cause turned out to be my incorrect syntax when using the npm request module.

Working with this code can be quite delicate. I initially tried the custom request option syntax: request(object, object).

To resolve the issue, I made the following adjustments:

    var request = require('request');

    var options = {
        method: 'POST',
        url: 'http://sampleurl.com/api/endpoint/',
        headers: {'id': 'TEST123',
            'sessionid': 'BK23JFQO921=',
            'Accept': 'application/json',
            'Accept-Language': 'en-us',
            'random': 'OIJRA9F'
        },
        body: '{ "data": [] }'
    };

    function handleResponse(error, response, body) {
        if (!error && response.statusCode == 200) {
            var parsedData = JSON.parse(body);
            console.log(response);
            console.log(parsedData);
        }
    }
    request(options, handleResponse);
};

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

Angular2 bootstrapping of multiple components

My query pertains to the following issue raised on Stack Overflow: Error when bootstrapping multiple angular2 modules In my index.html, I have included the code snippet below: <app-header>Loading header...</app-header> <app-root>L ...

Controller Not Deserializing Ajax File Upload in MVC 5

There seems to be an issue with deserializing the data sent using the multipart/form-data type within an MVC 5 project. Despite appearing valid in Fiddler, the data is not being mapped into the controller method. While debugging, it is evident that all par ...

Converting a dictionary to JSON and transmitting it to an HTML page with the help of

Is there a way to properly display a large Python dictionary in HTML using Flask for better readability? Here is an example dict: a={'a':True, 'b':False} a_json=json.dumps(a) # {"a": true, "b": false} return render_ ...

A pop-up blocker is preventing the new tab from opening

Below is my JavaScript code: $('#external-apply-job a').click(function(e) { var button = $(this); var url = $(this).data("system-url"); loadPreloader(); $.ajax({ url: url, ...

Using ng-repeat to randomize data displayed from Firebase

Recently, I've been thinking about creating a Firebase database to store quotes. My vision is to structure the data in a way that each quote object looks like this: quotes:{ ObjectId1:{ title: "When there's a will there's a way ...

Launching a Node.js script with pm2 and implementing a delay

Utilizing the amazing pm2 package to maintain the longevity of my node.js applications has been extremely helpful. However, I have encountered a problem that I am unsure how to resolve. One of my applications involves multiple scripts, a server, and sever ...

How feasible is it to develop a built-in browser within a webpage utilizing frameworks like React.js or Astro?

Is it possible to create a web application with 4 separate 'tiles', each functioning as its own web browser for accessing different websites? I am unfamiliar with how web browsers work and tried using npm packages like react-embedded-browser with ...

Php/JavaScript Error: Identifier Not Found

I've double-checked my code multiple times, but it still doesn't seem to be working properly. When the PHP runs, the browser console displays the following error: Uncaught SyntaxError: Unexpected identifier. I'm not sure if this is a si ...

Investigating and solving issues in Javascript and JQuery

Let me walk you through the JavaScript process I am working on: When a text is entered in the input bar and submitted, the script dynamically creates a new "div" element and places the text inside it. This new div is then appended to an existing div calle ...

Tips for streamlining ng-switch with comparable elements?

Here is the code snippet I'm working with: <span ng-switch="status"> <span ng-switch-when="NOT OK"> <span style="color: red;" ng-bind="status"></span> </span> <span ng-switch-when="OK"> ...

How to utilize Javascript to open a new view in ASP.NET MVC

Transitioning my thought process from WebForms to MVC, I am looking to achieve the following tasks: 1) Trigger a button click event that will 2) run some JavaScript code in order to 3) open a new browser window or tab displaying an existing view from the ...

Troubleshooting the malfunction of the CSS display property

I've created a div with a number displayed initially. When I hover over the div, the number disappears and a paragraph is revealed. Upon hovering out, the paragraph hides and the number reappears. My attempts to achieve this using CSS (display: none ...

Beginning point of horizontal scrolltop

Check out the link http://codepen.io/anon/pen/zGLZoR I have a "floating div" that moves along with the page scroll, but I want it to start floating only after the user has scrolled down 200px. Currently, it starts moving as soon as the scrollbar is moved. ...

Issues with Javascript functionality in Internet Explorer and Google Chrome

Hello everyone, I'm experiencing an issue with a thumb image link swapping out on hover. Oddly enough, it seems to work perfectly in Firefox and Safari, but it's not showing up on IE and Chrome. As I am relatively new to Javascript, I may be over ...

Implementing sliders for interactive functionality with an HTML table

I need to implement sorting and sliding features on an HTML table using jQuery. Sorting has already been achieved by utilizing the DataTable.js jQuery library. The challenge now is to incorporate a slider into the table, with all subject columns being scro ...

When utilizing a Javascript event listener within ReactJS with NextJS, the dynamically imported module without server-side rendering fails to load

Hello everyone, I am new to ReactJS and NextJS and would really appreciate some advice on the issue below. Thank you in advance! Here is my current tech stack: Node v16.6.1 React v17.0.2 Next.js v10.0.4 I'm working on implementing a carousel and si ...

Menu selection that changes dynamically based on radio button selection

Currently, I have four radio buttons and my goal is to have a drop-down menu change based on the selected radio button. Should I pre-write all the drop-down options and display them accordingly, or would it be better to use ajax to fetch the values from th ...

Trigger the opening of a class or window upon pressing the button

Good evening, I'm attempting to create a functionality where pressing a specific button will open a window. However, I am unsure of how to achieve this using CSS classes. My initial thought was to add a new class in the CSS file and call it every ti ...

A guide to using the css_selector method in Selenium webdriver to click on button webelements of the same type

When working with HTML, how can we click on a specific button within a div that has multiple buttons of the same type? For example: <div class="some-class"> <button type="button">Ok</button> <button type="button">Cancel< ...

Using setInterval to eliminate duplicate markers from a leaflet map

I have been working on a Leaflet map project with markers. The markers' latlng data is fetched from JSON and displayed correctly. I tried using setInterval to refresh the method every 5 seconds to update the latlng positions, ensuring that old marker ...