1
我是摩卡新手,但我看過他們支持諾言,但我似乎無法找到解決我的問題的任何文檔。我有一個驗證方法返回一個承諾。在我的測試中,我需要等到完成才能通過/失敗。用摩卡返回承諾的測試方法調用
這裏是我的身份驗證工廠:
(function() {
'use strict';
angular.module('app.authentication').factory('authentication', authentication);
/* @ngInject */
function authentication($window, $q, $location, authenticationData, Session) {
var authService = {
authenticate: authenticate
};
return authService;
function authenticate() {
var token = authenticationData.getToken();
var deferral = $q.defer();
if (!Session.userId && token) {
authenticationData.getUser(token).then(function(results) {
Session.create(results.id, results.userName, results.role);
deferral.resolve();
});
}
else{
deferral.resolve();
}
return deferral.promise;
}.........
這裏是我的測試:
describe('authentication', function() {
beforeEach(function() {
module('app', specHelper.fakeLogger);
specHelper.injector(function($q, authentication, authenticationData, Session) {});
});
beforeEach(function() {
sinon.stub(authenticationData, 'getUser', function(token) {
var deferred = $q.defer();
deferred.resolve(mockData.getMockUser());
return deferred.promise;
});
});
describe('authenticate', function() {
it('should create Session with userName of TestBob', function() {
authentication.authenticate().then(function(){
console.log('is this right?');
expect(Session.userName).to.equal('TesaatBob');
}, function(){console.log('asdfasdf');});
});
});
});
當我運行此,測試通過,因爲它永遠不會使它的承諾里,從來沒有碰到期待。如果我把「return authenication.authenticate ....」,那麼它超時錯誤。
謝謝
您需要爲'it'接受'done'參數,然後在完成後執行它,就像其他任何異步測試一樣。 – 2014-11-05 19:06:19
@凱文B,你有沒有例子? – Boone 2014-11-05 19:22:15
http://mochajs.org/#asynchronous-code注意該部分末尾的代碼,您可以簡單地返回承諾本身。 – 2014-11-05 19:23:17