Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a POST request from a Protractor test?

I would like to make a POST request (with JSON payload) to a database server prior to running a Protractor test, in order to inject test data. How can I do this, if at all possible?

like image 659
aknuds1 Avatar asked Feb 10 '14 22:02

aknuds1


People also ask

How do you call an API on a protractor?

Protractor runs on top of nodejs, and under the hood is calling Selenium API. You can use all of the node libraries, including request . Choose between import/require: import * as request from 'request'; var request = require('request');

Does protractor use karma?

Yes, you can use karma and protractor together. Karma is used for unit testing the component you created using angular command you can test those components using karma. Protractor is used for end to end test.


2 Answers

You can just use another library to run the POST request if you just want to populate your database.

For example, you can use superagent in your beforeEach like so:

var request = require( "superagent" );

describe( "Something", function() {

  beforeEach( function( done ) {
    request
      .post( "http://localhost/api/foo" )
      .send( {data : "something"} )
      .end( done );
  } );

} );
like image 59
Oliver Salzburg Avatar answered Sep 18 '22 10:09

Oliver Salzburg


I found a way to do it, with the help of Andres D. The gist of it is to run a script in the browser via browser.executeAsyncScript and inject the $http service in there. The $http service is then told to make a POST request. Here's example CoffeeScript of how it's done:

browser.get('http://your-angular-app.com')
browser.executeAsyncScript((callback) ->
  $http = angular.injector(["ng"]).get("$http")
  $http(
    url: "http://yourservice.com"
    method: "post"
    data: yourData
    dataType: "json"
  )
  .success(->
    callback([true])
  ).error((data, status) ->
    callback([false, data, status])
  )
)
.then((data) ->
  [success, response] = data
  if success
    console.log("Browser async finished without errors")
  else
    console.log("Browser async finished with errors", response)
)
like image 26
aknuds1 Avatar answered Sep 21 '22 10:09

aknuds1