gpt4 book ai didi

angularjs - 使用 $httpBackend 延迟响应

转载 作者:行者123 更新时间:2023-12-05 07:58:14 25 4
gpt4 key购买 nike

在我看来,我有加载动画,该动画一直显示到我收到来自 API 的响应。

//Displayed before we've received API response
<p ng-if="vm.vehicles == null">Loading ...</p>

//Displayed once we received response for the API
<table ng-if="vm.vehicles">
<tr ng-repeat="vehicle.vm.vehicles">...</tr>

为了进行测试,我使用了 $httpBackend Angular 模块。像这样:

$httpBackend.whenGET('api/vehicles').respond({vehicles: [...]});

问题

我想写一个测试来检查是否显示加载动画。

我试过:

expect(ptor.isElementPresent(By.cssContainingText('p', 'Loading'))).to.eventually.be.true;`

但我没有通过。所以我认为我需要有条件地延迟从 $httpBackend 获得的响应。

我找到了这篇博文 http://endlessindirection.wordpress.com/2013/05/18/angularjs-delay-response-from-httpbackend/

但是,插入该配置方法使我的所有测试都失败了(我认为是因为模板没有及时加载),它延迟了所有响应,所以这并不是我真正需要的。

那么我怎样才能延迟那个电话的响应呢?理想情况下,我只想为该测试延迟它。

最佳答案

查看$http的文档,特别是 拦截器

这是有趣的一点:

response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.

换句话说,您可以拦截响应而不是立即返回它,而是返回一个在超时后返回响应的 promise ...

例如plunkr example .

但是在端到端测试的情况下,你必须处理 $httpBackend对象。

这个位发挥作用:

As opposed to unit-testing, in an end-to-end testing scenario or in scenario when an application is being developed with the real backend api replaced with a mock, it is often desirable for certain category of requests to bypass the mock and issue a real http request (e.g. to fetch templates or static files from the webserver). To configure the backend with this behavior use the passThrough request handler of when instead of respond.

翻译:您可以使用 .passThrough() 并且您的拦截器应该可以工作:

$httpBackend.whenGET('api/vehicles').passThrough();

缺点是这会执行实际请求。

你也可以检查这个非常相似的问题: AngularJS - Using ngMockE2E $httpBackend how can I delay a specific response?

关于angularjs - 使用 $httpBackend 延迟响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25368691/

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