2017-07-30 58 views
0

我想單元測試我的角度服務使用async/await關鍵字在相應的(茉莉花)單元測試下面。原生Promise的測試工作得很好,但我幾乎堅持讓角色$q對應的工作。使用異步/等待與茉莉花的角度1.x單元測試

  • 角:1.6.5
  • 茉莉花:2.7.0
  • (無頭)鍍在MacOS:60.X

angular 
    .module('asyncAwaitTest', []) 
    .factory('xService', xServiceFactory); 

function xServiceFactory(
    $q, 
    $timeout 
) { 
    return { 
    getXAfter1Sec() { 
     return new Promise(resolve => setTimeout(() => resolve(43), 1000)); 
    }, 
    getXAfter1SecWithAngular$Q() { 
     const deferred = $q.defer(); 

     $timeout(() => deferred.resolve(43), 1000); 

     return deferred.promise; 
    } 
    }; 
} 

jasmine.DEFAULT_TIMEOUT_INTERVAL = 2000; 

describe('asyncAwaitTest: x service',() => { 
    let $timeout; 
    let xService; 

    beforeEach(() => { 
    module('asyncAwaitTest'); 

    inject(
     (
     _$timeout_, 
     _xService_ 
    ) => { 
     $timeout = _$timeout_; 
     xService = _xService_; 
     } 
    ); 
    }); 

    it('should work', async (done) => { 
    const x = await xService.getXAfter1Sec(); 

    expect(x).toEqual(43); 

    done(); 
    }); 

    it('should work, too. but y not?!!', async (done) => { 
    const xPromise = xService.getXAfter1SecWithAngular$Q(); 

    $timeout.flush(); 

    const x = await xPromise; 

    expect(x).toEqual(43); 

    done(); 
    }); 
}); 

小提琴這裏提供:https://jsfiddle.net/glenn/gaoh6bvc/

我試過谷歌,但它並沒有給我一個信號虛擬良導致

+0

'async/await'不知道'$ q'。他們與本土承諾一起工作。檢查了這一點:https://stackoverflow.com/questions/35629246/typescript-async-await-and-angular-q-service –

+0

我明白了。但有沒有解決方法?把'.run(function runBlock($ window,$ q){$ window.Promise = $ q;});'只會讓情況變得更糟 - 兩次測試都失敗:/ –

回答

2

您可以爲您的測試一個幫手,它把來自$q到本機的承諾的承諾。檢查出來here

it('should work, too. but y not?!!', async (done) => { 
    const xPromise = toNativePromise(xService.getXAfter1SecWithAngular$Q()); 

    $timeout.flush(); 

    const x = await xPromise; 

    expect(x).toEqual(43); 

    done(); 
}); 

function toNativePromise(promise) { 
    return new Promise((resolve, reject) => { 
    promise.then(val => { 
     resolve(val); 
    }, err => { 
     reject(err); 
    }); 
    }); 
} 
+0

我認爲這是一個可以接受的解決方法。謝謝! :) –

0

async功能基於原生承諾,而AngularJS使用$ q承諾。 await是一個鏈接承諾與then的語法糖。 $ q承諾鏈在測試中的摘要上執行。

不能被固定

await xPromise; 
$rootScope.$digest(); 

因爲$rootScope.$digest()直到執行$rootScope.$digest()不評估。這導致未決的承諾。

AngularJS首先不應該用async..await進行測試。 Angular被設計爲同步測試。

這是

it('...',() => { 
    ... 
    xPromise.then(x => { 
    expect(x).toEqual(43); 
    }); 
    $rootScope.$digest(); 
}); 

或承諾可以jasmine-promise-matchers被壓扁:

it('...',() => { 
    ... 
    expect(xPromise).toBeResolvedWith(43); 
    $rootScope.$digest(); 
});