gpt4 book ai didi

angularjs - 每次 AngularJS 测试执行 rootScope.digest() 或 httpBackend.flush() 时如何避免 'Error: Unexpected request: GET'

转载 作者:行者123 更新时间:2023-12-03 12:52:42 27 4
gpt4 key购买 nike

我所有的单元测试,而不是 E2E 测试,执行显式 rootScope.digest() 或 httpBackend.flush() 以刷新异步回调,遇到错误:

How to avoid the 'Error: Unexpected request: GET'
No more request expected

我估计是因为httpBackend调用了ui-router模板。我不知道它为什么要这样做。我不是要这个。我只希望它调用我的模拟 json 服务。

这个错误迫使我在每个 it() 块中有以下语句:
$httpBackend.whenGET(/\.html$/).respond('');  

必须有更整洁的方法。

特别是如果测试首先没有使用 $httpBackend :
  it('should return the list of searched users', function() {
// Always use this statement so as to avoid the error from the $http service making a request to the application main page
$httpBackend.whenGET(/\.html$/).respond('');

var users = null;
UserService.search('TOTO', 1, 10, 'asc', function(data) {
users = data.content;
});
$rootScope.$digest();
expect(users).toEqual(RESTService.allUsers.content);
});

测试通过了,但看起来很黑。或菜鸟:-)

编辑:另一个测试:
  it('should return the list of users', function () {
// Always use this statement so as to avoid the error from the $http service making a request to the application main page
$httpBackend.whenGET(/\.html$/).respond('');
// Create a mock request and response
$httpBackend.expectGET(ENV.NITRO_PROJECT_REST_URL + '/users/1').respond(mockedUser);
// Exercise the service
var user = null;
RESTService.User.get({userId: 1}).$promise.then(function(data) {
user = data;
});
// Synchronise
$httpBackend.flush();
// Check for the callback data
expect(user.firstname).toEqual(mockedUser.firstname);
expect(user.lastname).toEqual(mockedUser.lastname);
});

最佳答案

这显然是设计使然,您的测试应该检查是否正在进行 HTTP 调用以及它们是否正在请求正确的 URL。而不是检查是否向 /\.html$/ 发出请求为什么不检查是否向 发出请求?正确 端点?无论是指令部分还是 API 调用。

如果你坚持扔掉可能有用的测试,你可以移动你的 whenGET()beforeEach() .

关于angularjs - 每次 AngularJS 测试执行 rootScope.digest() 或 httpBackend.flush() 时如何避免 'Error: Unexpected request: GET',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29634780/

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