返回带有mocha的promise的测试方法调用
Test method call that returns a promise with mocha
我是Mocha的新手,但我现在读到他们支持承诺,但我似乎找不到任何解决我问题的文档。我有一个返回promise的authenticate方法。在我的考试中,我需要等到考试结束才能通过/不通过
这是我的身份验证工厂:
(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…",那么它会超时出错。
感谢
角度承诺直到下一个摘要周期才会得到解决。
请参阅http://brianmcd.com/2014/03/27/a-tip-for-angular-unit-tests-with-promises.html:
在单元测试Angular时,您会很快遇到一件事应用程序是在某些情况下需要手动启动摘要循环情况(通过scope.$apply()或scope$digest())。不幸的是其中一种情况是承诺解决,这不是很明显开始Angular开发人员。
我认为添加$rootScope.$apply()
应该可以解决您的问题,并在不需要异步测试的情况下强制执行promise解决方案。
相关文章:
- 函数在promise被解析后被调用,但Jasmine未通过测试.为什么?
- AngularJS和promise值在调用本地函数时的效果-未定义
- 多次调用方法后返回相同promise的模式
- 我如何防止错误“;未捕获(在promise中)DOMException:play()请求被对pause()的调用中断&”
- 多次调用promise函数,直到另一个promise函数满足条件
- bluebird promise catch() 没有使用 Promise.CancelError 调用内部函数
- 使用 Promise 在另一个函数中调用带有 Bluebird 承诺库的函数
- JavaScript Promise 解析并拒绝函数调用序列
- 使用promise或setTimeout确定延迟函数的调用顺序
- 使用Node中的Q promise库对值数组顺序调用/执行相同的函数;并返回带有结果的新数组/集合
- Javascript Promise().然后防止在执行第一个调用之前重新调用该函数
- 当使用promise时,为什么最后一个会被调用
- 在 Promise 调用的错误函数回调后附加对象的用法是什么
- 使用 Javascript Promise 调用多个 WEB API 调用
- Typescript async/await Promise调用差异
- 为什么不't运行此promise调用之后的代码
- Javascript的Promise调用出现了Promise混淆
- 应该由Promise调用同步代码.然后创建一个新的Promise
- 如何组织递归promise调用
- window.open()在从promise调用时被浏览器阻止