茉莉花。角度服务。角度承诺。如何让他们一起玩?

时间:2016-06-15 02:28:28

标签: angularjs unit-testing ionic-framework jasmine karma-runner

我关注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。不是测试承诺。

1 个答案:

答案 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中调用它。