[英]How to unit test a function with a promise and callback function with Angular
Bit stumped on how to combine $httpBackend and promises with unit tests. 有点困惑如何将$ httpBackend和promise与单元测试结合起来。 The function I'm trying to test (in a controller) is: 我要测试的功能(在控制器中)是:
vm.getData = (callback) => {
$http.get('http://localhost:3000/cars?_start=0&_end=100').then(result => {
return callback(result.data);
});
};
The test that's failing looks something like this... 失败的测试看起来像这样...
describe('controllerToTest', () => {
beforeEach(() => {
angular.module('test', [])
.controller('controllerToTest', require('./controllerToTest'));
});
beforeEach(angular.mock.module('test'));
beforeEach(angular.mock.inject($injector => {
$rootScope = $injector.get('$rootScope').$new(true);
$q = $injector.get('$q').defer();
$httpBackend = $injector.get('$httpBackend');
$httpBackend.when("GET", "http://localhost:3000/cars?_start=0&_end=100").respond({});
vm = $injector.get('$controller')('controllerToTest', {});
}));
it('should return the callback function', () => {
let whatAmI = null;
let callbackFn = () => {
whatAmI = 'boom'
};
$q.resolve(
(x) => {
return x();
}
);
vm.getData(callbackFn);
$rootScope.$digest();
expect(whatAmI).toEqual('boom');
});
}
$httpBackend
doesn't return result synchronously. $httpBackend
不同步返回结果。 To get response from pending $httpBackend
requests $httpBackend.flush()
method should be used: 要获得未决的$httpBackend
请求的响应,应使用$httpBackend.flush()
方法:
...
vm.getData(callbackFn);
$httpBackend.flush();
$rootScope.$digest();
expect(whatAmI).toEqual('boom');
...
Just make sure $httpBackend
is available in it
function's scope 只要确保$httpBackend
在it
功能范围内可用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.