我发现有几篇文章将这段代码展示为一种进行异步单元测试的方式:
服务:
angular.module('miservices', [])
.service('myAppServices', ['$http', 'httpcalls', function($http, httpcalls) {
this.getAccountType = function(){
return httpcalls.doGet('http://localhost:3010/...').then(function(data){
return data;
}, function(error){
...
});
};
...
测试:
describe('testing myAppServices', function(){
beforeEach(module('smsApp'));
it('should handle names correctly', inject(function(myAppServices){
myAppServices.getAccountType()
.then(function(data) {
expect(data).equal({...});
});
...
我们正在使用 AngularJS、Mocha、Chai 并且我们安装了 Sinon。
测试永远不会到达 .then
部分,但为什么呢?
谢谢!
最佳答案
如果您正在测试您的服务,我建议模拟您的“httpcalls”服务(因为它超出了本次测试的范围)。
要模拟它,您可以采用多种方法,一种方法是拥有一个仅在单元测试中使用的模拟模块。
angular.module('miservices.mocks', [])
.service('httpcalls', ['$q', function($q) {
this.returnGet = '';
this.doGet = function(url) {
return $q.when(this.returnGet);
};
};
然后您的单元测试将类似于:
describe('testing myAppServices', function(){
beforeEach(function() {
module('smsApp');
module('miservices.mocks');
});
it('should handle names correctly', inject(function(myAppServices, httpcalls){
httpcalls.returnGet = 'return data';
myAppServices.getAccountType()
.then(function(data) {
expect(data).equal('return data');
});
...
因为我们在应用程序模块之后插入 mocks 模块,httpcalls 服务被其模拟版本覆盖,并允许我们正确测试 myAppServices 而无需进一步的依赖。
关于AngularJS、 Mocha 、 Chai : testing service with promises,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33301508/