【发布时间】:2016-11-20 10:27:51
【问题描述】:
我为后端角度测试设置了 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 钩子抛出 Unsatisfied 请求。
我对此的理解可能完全不正确,因此请随时教育我正确的方法(这是我的方法):
1) 需要所有必要的依赖项。
2) 注入它们并设置一个 $httpBackend 侦听器,该侦听器会在触发真正的 http 时触发测试响应。
3) $rootScope.$apply() 任何承诺,因为它们的解决方案与角度生命周期相关。
4) 每个设置监听器之前的第一个,每个触发服务之前的第二个,该服务触发 $http 允许 $httpBackend 触发并设置 mockResponse。
5) 测试模拟响应。
【问题讨论】:
-
$httpBackend.flush()调度响应。 docs.angularjs.org/api/ngMock/service/$httpBackend
标签: javascript angularjs mocha.js chai httpbackend