Javascript 返回mocha承诺的测试方法调用
我是摩卡新手,但我读到他们现在支持承诺,但我似乎找不到任何解决我问题的文档。我有一个返回承诺的authenticate方法。在我的测试中,我需要等到测试完成后才能通过/不通过 这是我的工厂:Javascript 返回mocha承诺的测试方法调用,javascript,angularjs,mocha.js,sinon,Javascript,Angularjs,Mocha.js,Sinon,我是摩卡新手,但我读到他们现在支持承诺,但我似乎找不到任何解决我问题的文档。我有一个返回承诺的authenticate方法。在我的测试中,我需要等到测试完成后才能通过/不通过 这是我的工厂: (function() { 'use strict'; angular.module('app.authentication').factory('authentication', authentication); /* @ngInject */ function authentication($win
(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 authentication.authenticate…”,则会出现超时错误
谢谢在下一个摘要周期之前,角度承诺不会得到解决 见: 单元测试时,您会很快遇到一件事 应用程序需要在某些情况下手动启动消化循环 情况(通过作用域$apply()或作用域$digest()。不幸的是,一个 在这些情况中,承诺解决是不太明显的 给刚开始的开发人员
我相信添加一个
$rootScope.$apply()
应该可以解决您的问题并强制承诺解决,而不需要异步测试。您需要接受一个done
参数到it
,然后在完成时执行它,就像任何其他异步测试一样。@Kevin B,您有一个例子吗?注意这一部分末尾的代码,您可以简单地返回承诺本身。这让我回到超时的错误。PhantomJS 1.9.7(Mac OS X)身份验证应创建用户名为TestBob的会话失败超时超过2000毫秒