gpt4 book ai didi

AngularJS 错误 : Unexpected request (No more requests expected)

转载 作者:行者123 更新时间:2023-12-04 12:20:24 29 4
gpt4 key购买 nike

在我的 AngularJS 应用程序中,我无法弄清楚如何对 then promise 的执行更改 location.url 进行单元测试。我有一个函数,登录 ,调用服务,身份验证服务 .它返回 promise ,然后 promise 的执行会改变 location.url。

这是 Controller 认证控制 :

angular
.module('bloc1App')
.controller('AuthCtrl', ['$scope', '$http','$location', 'AuthenticationService',
function($scope, $http, $location, AuthenticationService) {

this.AuthenticationService = AuthenticationService;
var self = this;

$scope.login = function(username, password){
self.AuthenticationService
.login(username, password)
.then(function(){
$location.url('/tasks');
});
};
}
]);

这是我在单元测试中的尝试:
    describe('Controller: AuthCtrl', function () {

var scope,
location,
route,
q,
rootScope,
AuthCtrl;

beforeEach(module('bloc1App'));

beforeEach(inject(function($controller, $rootScope, $location, $route, $q) {
scope = $rootScope.$new();
q = $q;
rootScope = $rootScope;
location = $location;
route = $route;

AuthCtrl = $controller('AuthCtrl', {
$scope: scope,
$route: route,
$location: location
});

}));

it('login should redirect user to tasks view', function(){
var deferred = q.defer();
spyOn(AuthCtrl.AuthenticationService, 'login').andReturn(deferred.promise);
spyOn(location, 'url');
scope.login('foo', 'foo');
deferred.resolve();
scope.$apply();
expect(location.url).toHaveBeenCalledWith('/tasks');
});
});

当我运行这个测试时,我得到了这个错误。如果我使用 rootScope.$apply() 代替,我会得到同样的错误:
Error: Unexpected request: GET views/AuthView.html
No more request expected

当我取出 scope.$apply() 时,我收到此错误:
Expected spy url to have been called with [ '/tasks' ] but it was never called.

有想法该怎么解决这个吗?这是我第一次对 Promise 进行单元测试,我可能在概念上误解了如何执行此操作。

预先感谢您的帮助。

最佳答案

当您使用 AngularJS 进行单元测试时,您实际上是在使用来自 ngMock 的模拟服务。模块而不是真正的服务。在这种情况下,您的错误可能来自 $httpBackend 模拟,如果您希望测试单元使用 $http,则必须首先“启动”发送真实的请求。 (我在任何地方都没有看到您使用 $http 的代码,所以我猜这里有一部分您没有显示。)

基本上,你需要告诉 $httpBackend使用 $httpBackend.when 模拟您期待特定请求(或者您可以使用 $httpBackend.expect ,如果您希望模拟检查请求是否真的被调用)以及应该返回什么响应。

因此,您的错误与 promise 无关,而与连接到服务器的测试单元有关。

关于AngularJS 错误 : Unexpected request (No more requests expected),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27471016/

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