![](/img/trans.png)
[英]How to unit test condition in promise then() karma and jasmine
[英]How to get karma/jasmine unit tests working with a callback after a promise?
我正在用AngularJS 1.5,JavaScript和Cordova編寫應用程序。
我想編寫一個單元測試,以檢查在promise之后是否執行了某些代碼。
這是我的代碼筆: https ://codepen.io/aubz/pen/yrxqxE
我不知道為什么,但是單元測試一直說這個錯誤:預期的間諜tryGeoClocking已被調用。
這很奇怪,因為控制台日志會打印出來,因此實際上是在調用該函數。
it('if location services are on, proceed', function () {
spyOn(CordovaDiagnostics, 'getLocationServicesStatus').and.callFake(function () {
return Promise.resolve(true);
});
spyOn(Clocking, 'attemptGeoClocking').and.callFake(function () {});
Clocking.geolocationClocking();
expect(Clocking.attemptGeoClocking).toHaveBeenCalled();
});
function geolocationClocking() {
CordovaDiagnostics
.getLocationServicesStatus()
.then(attemptGeoClocking)
.catch(function () {});
}
function attemptGeoClocking() {
console.log(' here ');
}
基本上,您在監視錯誤的功能。 讓我重命名一些內容,以便更清楚地了解您的工作:
function Clocking(CordovaDiagnostics) {
return {
geolocationClocking: geolocationClocking,
attemptGeoClockingOUTER: attemptGeoClockingINNER//private API
};
function geolocationClocking() {
CordovaDiagnostics
.getLocationServicesStatus()
.then(attemptGeoClockingINNER)
.catch(function () {});
}
function attemptGeoClockingINNER() {
console.log(' here ');
}
}
並在測試中:
spyOn(Clocking, 'attemptGeoClockingOUTER').and.callFake(function () {
console.log('calling fake')
});
如您所見,您的代碼在OUTER上進行監視,但是geolocationClocking
從不調用OUTER,它使用的是INNER:
CordovaDiagnostics
.getLocationServicesStatus()
.then(attemptGeoClockingINNER)
您需要以某種方式對代碼進行重做,以使其內部使用與測試中存根的功能相同的功能。 這是一個有效的Codepen: https ://codepen.io/anon/pen/xeyrqy ? editors = 1111
注意:我還用$q.when
替換了Promise.resolve
,並添加了$rootScope.$apply()
,這是解決承諾所必需的。
添加我在這里所做的更改,以防codepen消失:
我已將工廠更改為服務(雖然不是必需的,但在這種情況下,我更喜歡使用服務):
myApp.service("Clocking", Clocking);
function Clocking(CordovaDiagnostics) {
this.geolocationClocking = function() {
CordovaDiagnostics
.getLocationServicesStatus()
.then(() => this.attemptGeoClocking())
.catch(function () {});
}
this.attemptGeoClocking = function() {
console.log(' here ');
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.