2015-11-27 79 views
7

我有一個問題,其中我的代碼混合ES6承諾與Angular promise,並且它在生產中工作,我無法編寫單元測試通過。

這段代碼演示了兩個實例,其中茉莉單元測試會失敗,但代碼工作正常生產:

// An angular $q promise 
    var f1 = function() { 
    return $q(function(resolve, reject) { 
     resolve('This is function 1!'); 
    }); 
    } 

    // An ES6 promise 
    var f2 = function() { 
    return new Promise(function(resolve, reject) { 
     resolve('This is function 2!'); 
    }); 
    } 

    // An angular $q.all() promise, attempting to resolve a $q and ES6 promise. 
    var s1 = function() { 
    return $q.all([f1(), f2()]).then(function() { 
     return '$q resolved both promises!' 
    }); 
    } 

    // An ES6 promise attempting to resolve a $q and an ES6 promise. 
    var s2 = function() { 
    return Promise.all([f1(), f2()]).then(function() { 
     return 'ES6 resolved both promises!' 
    }); 
    } 

測試看起來像:

describe('Testing mixed ES6 promises and Angular $q', function() { 
    var $scope = null; 
    var service = null; 

    //you need to indicate your module in a test 
    beforeEach(module('plunker')); 

    beforeEach(inject(function($rootScope, _testService_) { 
    $scope = $rootScope.$new(); 
    service = _testService_; 
    })); 

    afterEach(function() { 
    }); 

    it('should resolve f1', function(done) { 
    var t1 = service.f1(); 
    t1.then(function() { 
     done(); 
    }); 
    $scope.$apply(); 
    }); 

    it('should resolve f2', function(done) { 
    var t1 = service.f1(); 
    t1.then(function() { 
     done(); 
    }); 
    $scope.$apply(); 
    }); 

    it('should resolve s1', function(done) { 
    var t1 = service.s1(); 
    t1.then(function() { 
     done(); 
    }); 
    $scope.$apply(); 
    }); 

    it('should resolve s2', function(done) { 
    var t1 = service.s2(); 
    t1.then(function() { 
     done(); 
    }); 
    $scope.$apply(); 
    }); 

}); 

這Plunker有一個工作演示: http://plnkr.co/edit/xhRc7O

請注意,前2次測試通過,因爲它們很直接ES6或$ q promi SES。

然後注意到每個其他測試都失敗了,因爲我以不同的方式混合使用了ES6和$ q promise。

最後,請注意,在控制器中,我證明兩個FAILING測試確實在生產中起作用。

爲什麼Angular不讓我在測試中混合使用ES6和$ q promise,但在生產代碼中沒有問題?

+0

您是否嘗試瞭解問題?也許這是一個錯誤,你設計了一個非常簡單的方法來重現它。 – atoth

回答

1

我也遇到這個問題,我的單元測試。在解釋問題並解決問題之前,我使用了一種解決方法:

if (window.Promise !== $q) { 
     window.Promise = $q; 
    } 
+0

這對我有效,但我在Jasmine創建這個問題,希望他們能夠創建一個適當的修復:https://github.com/jasmine/jasmine/issues/1200 – yukw777

+0

@ yukw777不要忘記恢復它afterEach函數中的原始值。否則,由於在不同的角度上下文中創建$ q,其他測試可能會失敗。 – Eduard