我关注this example。
我们有测试套件,如:
describe('Basic Test Suite', function(){
var DataService, httpBackend;
beforeEach(module('iorder'));
beforeEach(inject(
function (_DataService_, $httpBackend) {
DataService = _DataService_;
httpBackend = $httpBackend;
}
));
//And following test method:
it('should call data url ', function () {
var promise = DataService.getMyData();
promise.then(function(result) {
console.log(result, promise); // Don't gets here
}).finally(function (res) {
console.log(res); // And this is also missed
})
})
});
如何让jasmine + karma与angular服务一起工作,返回promise?
我见过this question,但看起来就是在测试用例中使用promises。不是测试承诺。
答案 0 :(得分:2)
你需要告诉jasmine您的测试是异步的,以便等待承诺解决。您可以通过在测试中添加done
参数来执行此操作:
describe('Basic Test Suite', function(){
var DataService, httpBackend;
beforeEach(module('iorder'));
beforeEach(inject(
function (_DataService_, $httpBackend) {
DataService = _DataService_;
httpBackend = $httpBackend;
}
));
//And following test method:
it('should call data url ', function (done) {
var promise = DataService.getMyData();
promise.then(function(result) {
console.log(result, promise); // Don't gets here
done();//this is me telling jasmine that the test is ended
}).finally(function (res) {
console.log(res); // And this is also missed
//since done is only called in the `then` portion, the test will timeout if there was an error that by-passes the `then`
});
})
});
通过向测试方法添加done
,您可以让jasmine知道它是异步测试,它会等到调用done
或超时。我通常只是在done
中调用then
,并依靠超时来测试失败。或者,我相信您可以使用某种错误对象调用done
,这也会导致测试失败,因此您可以在catch
中调用它。