У меня есть 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 приводит к таймауту мокко (2000 мс), а хук afterEach вызывает неудовлетворенный запрос.
Мое понимание этого может быть совершенно неправильно поэтому, пожалуйста, не стесняйтесь, чтобы обучить меня правильному подходу (здесь был мой подход):
1) требует, чтобы все необходимые зависимости.
2) вводят их и настраивают прослушиватель $ httpBackend, который запускает тестовый отклик при запуске реального http.
3) $ rootScope. $ Apply() любые обещания, поскольку их разрешение привязано к угловому жизненному циклу.
4) первый перед каждым устанавливает слушателя, второй перед каждым запускает службу, которая запускает $ http, разрешая $ httpBackend запускать и устанавливает mockResponse.
5) испытательный макет ответа.
'$ httpBackend.flush()' посылает ответы. https://docs.angularjs.org/api/ngMock/service/$httpBackend – thebearingedge