【发布时间】:2015-10-23 11:44:22
【问题描述】:
我发现了几篇将这段代码作为异步单元测试方式的帖子:
服务:
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 部分,但为什么呢?
谢谢!
【问题讨论】:
-
问题不是promise,而是$http。你必须模拟请求,但你不这样做。
-
你的意思是httpBackend他们吗?
-
没错。如果 doGet 和 getAccountType 对实际的 http 响应没有任何作用,您可以跳过此规范并模拟 getAccountType 以获取其他规范。
-
谢谢@estus!最后一个问题:如果我们确实需要测试来自后端的真实响应怎么办?
-
保存它以供 e2e 使用,这就是要在那里测试的内容。
标签: angularjs testing mocha.js karma-runner chai