2016-07-17 3 views
0

jsdom/mocha/chai가 백엔드 각도 테스트를 위해 설정되었습니다.

app.service('testService', ['config', '$http', function(config, $http) { 
    function getSpecificConfig(type) { 
     return config.getConfig() 
     .then(function(config) { 
      // config is coming back defined; 
      // $http timesout 
      return $http({method: 'post', url: 'http://localhost:2222/some/path', withCredentials: true}); 
     }) 
     .then(function(res) { 
      return res.data.config[type]; 
     }) 
     .catch(function(err) { 
      //handles err 
     }); 
    }; 

    return { 
     getConfig: getConfig 
    } 
}]); 

내 테스트는 다음과 같습니다 :

/* jshint node: true */ 
/* jshint esversion: 6 */ 

let helpers = require(bootstrapTest), 
    inject = helpers.inject, 
    config, 
    specificConfig, 
    mockResponse, 
    $httpBackend, 
    $rootScope; 

//config service 
require('config.js'); 

//testService I'm testing 
require('testService'); 

beforeEach(inject(function($injector, _$httpBackend_) { 
    config = $injector.get('config'); 
    specificConfig = $injector.get('testService'); 
    $rootScope = $injector.get('$rootScope'); 
    $httpBackend = _$httpBackend_; 

    $httpBackend.when('POST', 'http://localhost:2222/some/path') 
    .response(function(data) { 
     //would like this to fire 
     console.log('something happened'); 
     mockResponse = {data: 'some data'}; 
     return mockResponse; 
    }); 
})); 

afterEach(function() { 
    $httpBackend.verifyNoOutstandingExpectations(); 
    $httpBackend.verifyNoOutstandingRequest(); 
}); 

describe ('this service', function() { 
    beforeEach(function() { 
     $httpBackend.expect('POST', 'http://localhost:2222/some/path'); 
     $rootScope.$apply(function() { 
      return specificConfig('something'); 
     }); 
    }); 

    it ('returns the specific config', function() { 
     expect(mockResponse).to.equal('some data'); 
    }) 
}); 

문제 : 테스트가 실행되면, config.getConfig

나는 기본적으로이 (의도적으로 사후 데이터)를하지 않는 서비스를()가 제대로 해석되지만 $ http는 모카 타임 아웃 (2000ms)으로 이어지고 afterEach 후크는 만족하지 않는 요청을 던집니다. 이것의

나의 이해는 올바른 접근 방식에 저를 교육 주시기 바랍니다 그래서 완전히 잘못 될 수 있습니다 (여기 내 접근했다) :

1) 필요한 모든 종속성을 필요로한다.

2) 실제 HTTP가 실행될 때 테스트 응답을 시작하는 $ httpBackend 수신기를 설정하고 설정합니다.

3) $ rootScope. $ apply() 이들의 해상도는 각 각의 수명주기와 관련이 있습니다.

4) 각각은 청취자를 설정하기 전에 첫 번째는 청취자를 설정하기 전에 두 번째는 $ http를 발생시키는 서비스를 시작하고 $ httpBackend는 mockResponse를 설정하고 설정합니다.

5) 시험 모의 반응. 당신이 당신의 조롱 HTTP 요청에서 약속을 반환해야하는 경우

+0

'$ httpBackend.flush()'응답을 전달합니다. https://docs.angularjs.org/api/ngMock/service/$httpBackend – thebearingedge

답변

0

당신과 같이 angular-mocks-async를 사용할 수 있습니다

var app = ng.module('mockApp', [ 
    'ngMockE2E', 
    'ngMockE2EAsync' 
]); 

app.run([ '$httpBackend', '$q', function($httpBackend, $q) { 

    $httpBackend.whenAsync(
     'GET', 
     new RegExp('http://api.example.com/user/.+$') 
    ).respond(function(method, url, data, config) { 

     var re = /.*\/user\/(\w+)/; 
     var userId = parseInt(url.replace(re, '$1'), 10); 

     var response = $q.defer(); 

     setTimeout(function() { 

      var data = { 
       userId: userId 
      }; 
      response.resolve([ 200, "mock response", data ]); 

     }, 1000); 

     return response.promise; 

    }); 

}]);