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

后端 未结 4 1340
情深已故
情深已故 2020-12-15 07:57

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 p

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 09:00

    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)
    )
    

提交回复
热议问题