gpt4 book ai didi

javascript - 使用 mocha 返回 promise 的测试方法调用

转载 作者:行者123 更新时间:2023-11-30 12:33:46 25 4
gpt4 key购买 nike

我是 Mocha 的新手,但我读到他们现在支持 promise,但我似乎找不到任何可以解决我的问题的文档。我有一个返回 promise 的身份验证方法。在我的测试中,我需要等到完成才能通过/失败。

这是我的身份验证工厂:

(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');});
});
});
});

当我运行它时,测试通过了,因为它从未在 promise 中实现并且从未达到预期。如果我输入“return authenication.authenticate ....”,那么它会因超时而出错。

谢谢

最佳答案

直到下一个摘要周期,Angular promises 才会得到解决。

参见 http://brianmcd.com/2014/03/27/a-tip-for-angular-unit-tests-with-promises.html :

One thing that you'll quickly run into when unit testing Angular applications is the need to hand-crank the digest cycle in certain situations (via scope.$apply() or scope.$digest()). Unfortunately, one of those situations is promise resolution, which is not very obvious to beginning Angular developers.

我相信添加一个 $rootScope.$apply() 应该可以解决您的问题并强制执行 promise 解析,而无需进行异步测试。

关于javascript - 使用 mocha 返回 promise 的测试方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26764886/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com