返回带有mocha的promise的测试方法调用

Test method call that returns a promise with mocha

本文关键字:promise 调用 测试方法 mocha 返回      更新时间:2023-09-26

我是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解决方案。