gpt4 book ai didi

AngularJS 单元测试基础 : testing for a $q deferred object's resolution and rejection in a service

转载 作者:行者123 更新时间:2023-11-28 20:23:36 25 4
gpt4 key购买 nike

我正在学习 angularJS 单元测试,并且正在努力对“AuthenticationService”服务上的基本“登录”功能进行单元测试。

服务方法使用 $q.defer() 设置 promise ,然后根据输入拒绝或解决它。

我如何监视或以其他方式测试该 promise ?

下面有什么问题?测试失败 - 错误是“未定义”而不是“AuthenticationService.login - 缺少参数”

希望我想做的事情很明显,我真的无法用语言表达。

服务

angular.module('moduleName').factory('AuthenticationService', function($q, $http) {
var serviceObject = {
login = function(credential, password) {
var d = $q.defer();

// check if any fields are missing
if (!credential && !password || credential === '' || password === '') {
d.reject('AuthenticationService.login - missing argument');
} else {
var sacho = {message: "I'm so confused"};
d.resolve(sacho);
}

return d.promise;
}
}
};

return serviceObject;
});

测试

describe('AuthenticationService', function()
{
var scope, AuthenticationService, $httpBackend;

beforeEach(inject(function($rootScope, _AuthenticationService_, _$httpBackend_) {
scope = $rootScope.$new();
AuthenticationService = _AuthenticationService_;
MemberLookup = _MemberLookup_;
$httpBackend = _$httpBackend_;
}));

describe('Logging In', function() {
it('promise should be rejected if any fields are empty', function() {
AuthenticationService.login('','').catch(function(error){
expect(error).toEqual('AuthenticationService.login - missing argument');
});
});
});
});

编辑 AuthenticationService.login 返回 promise 。

如果该方法的任一凭据为空或缺失,则应拒绝 promise 。

在测试代码(下方)中,我尝试编写一个测试来查看 promise 是否被拒绝。测试输入空白字符串作为 AuthenticationService.login 方法的参数。预期的行为是 promise 被字符串 'AuthenticationService.login - missing argument' 拒绝。但是,运行测试失败 - Authentication.Service.login('','').catch 的回调未按预期工作。

我也尝试过使用 .then(null, callback)

当给定特定时,我如何监视 AuthenticationService.login 返回的 promise 参数?

最佳答案

it('promise should be rejected if any fields are empty', function(done) {
AuthenticationService.login('','').catch(function(error){
expect(error).toEqual('AuthenticationService.login - missing argument');
done()
});
scope.$digest()
});

完成 - 说明您在准备就绪时测试框架(在异步操作的情况下)

scope.$digest() - 解决所有的 promise

关于AngularJS 单元测试基础 : testing for a $q deferred object's resolution and rejection in a service,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24724236/

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