私は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 timeout(2000ms)になり、afterEachフックは不満足な要求をスローします。この
私の理解が正しいアプローチで私を教育すること自由に感じなさいので、完全に間違っている可能性があります(ここでは私のアプローチだった):
1)は、必要なすべての依存関係が必要です。
2)それらを注入し、実際のhttpが起動されたときにテスト応答を起動する$ httpBackendリスナーを設定します。
3)$ rootScope。$ apply()それらの解決策としての約束事は、角のライフサイクルに結びついています。
4)それぞれがリスナーを設定する前に、最初はリスナーを設定し、2回目は$ httpを起動するサービスを起動し、$ httpBackendを起動してmockResponseを設定します。
5)テスト模擬応答。あなたが嘲笑HTTPリクエストに約束を返却する必要がある場合は
'$ httpBackend.flush()'レスポンスを送出します。 https://docs.angularjs.org/api/ngMock/service/$httpBackend – thebearingedge