![](/img/trans.png)
[英]How Chain Map or Chain Filter inside of Angular Http request that returns a promise
[英]Testing angular $http inside promise chain with mocha
我為后端角度測試設置了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導致mocha超時(2000毫秒),並且afterEach鈎子引發未滿足的請求。
我對此的理解可能是完全不正確的,因此請隨時教育我正確的方法(這是我的方法):
1)需要所有必要的依賴項。
2)注入它們並設置一個$ httpBackend偵聽器,當真實的http被觸發時,它會觸發測試響應。
3)$ rootScope。$ apply()任何承諾,因為它們的解析度與角度生命周期相關。
4)第一個在每個設置偵聽器之前,第二個在每個觸發服務之前,后者觸發$ http允許$ httpBackend觸發並設置嘲笑響應。
5)測試模擬響應。
如果您需要在模擬的 HTTP請求中返回Promise,則可以使用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;
});
}]);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.