Mocking a server response

1.2k views Asked by At

I'm new to e2e testing. I've encountered problem during my protractor tests. My web application calls API despite my efforts:

Started GET "/api/programs" for 127.0.0.1 at 2015-06-22 10:43:19 +0200
Processing by Api::V1::ProgramsController#index as JSON
======= NO Authorization token =======

I want to provide my web application with a correct HTTP POST response. Yet my code is not working:

Here is my code:

describe('e2e tests', function() {
it('FO tests', function() {

browser.addMockModule('WebClientApp', function() {
  console.log('test');
  angular.module('WebClientApp', ['ngMockE2E'])
  .run(function($httpBackend) {

    console.log('Test2!');
    alert('Test3!');

    $httpBackend.when('POST','api/auth/current_resource')
      .respond(200, [{

          "resource":
          {"id":"e11e5e4a-034c-4545-967a-dae395d5c950","email":"[email protected]","name":"Xaa","surname":"Xaaaa","is_active":true,"personal_number":null,"resource_name":"User","roles":"admin"}

          "token": "AdPnyXvZZDtcPkMVE9rIDFM09WmHubAnEd4wGXLPMiPWrFu0gDH1uIg7lqXXl1k2UgmJ1ektHf3Pduq2iF0nsR3A4yJ1dw8cB2FHgw3rWMf3q4357Atg9FtC7WnHisGa"
          }]);

    $httpBackend.whenGET(/.*/).passThrough();
  });
});

browser.getRegisteredMockModules();
browser.get('http://0.0.0.0:9000/#/back-office/dashboard');

browser.pause();
});
});

And my Request:

Remote Address:0.0.0.0:3000
Request URL:http://0.0.0.0:3000/api/auth/sign_in
Request Method:OPTIONS
Status Code:200 OK
Response Headers
view source
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:accept, content-type
Access-Control-Allow-Methods:GET, PUT, DELETE, POST, OPTIONS
Access-Control-Allow-Origin:http://localhost:9000
Access-Control-Max-Age:1728000
Content-Type:text/plain
Transfer-Encoding:chunked
X-Request-Id:1c75d93d-4539-4654-9963-a04bf45defe0
X-Runtime:0.029612
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Access-Control-Request-Headers:accept, content-type
Access-Control-Request-Method:POST
Connection:keep-alive
Host:0.0.0.0:3000
Origin:http://localhost:9000
Referer:http://localhost:9000/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36
1

There are 1 answers

0
Matias Fernandez Martinez On BEST ANSWER

Here is a possible work around if the problem is CORS. (I don't believe tat $httpBackend is prepare for that use).

But can you provide the code of the service which is calling: /api/programs ? Maybe you are missing to mock other web services responses, which are been executed by some angular factory/service etc.

Update:

@Dan Kanze answer that for cross domain request you can use expectJSONP.

Here is his example code

httpBackend.expectJSONP('http://api.stackexchange.com/2.1/users/gigablox/timeline?callback=JSON_CALLBACK')
.respond(returnData);