AngularJS 与 $resource 和 $httpBackend 的奇怪行为

标签 angularjs jasmine angular-resource

我有以下 AngularJS 资源作为服务公开

 myServices.factory('Service1', ['$resource',
    function ($resource) {

        var Registrations = $resource('/api/v1/registration/:id');

        return {
            getForTcn: function(tcn) {
                return Registrations.query({ tcn: tcn, state: 'Active' }).$promise;
            }

        };
    } ]);

我的 Jasmine 测试失败了

beforeEach(inject(function (_$httpBackend_, Service1) {
    $httpBackend = _$httpBackend_;
    service = Service1;

    $httpBackend.when('GET', /^\/api\/v1\/registration\?.*/).respond([]);
}));afterEach(function () {
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
});

使用上面的设置,下面的断言失败

it('should have correct http GET request', function () {
    Service.getForTcn('1234');
    $httpBackend.expectGET('/api/v1/registration?tcn=1234&State=Active');
    $httpBackend.flush();
});

如果我交换服务函数和断言中参数的位置,测试就会通过。

getForTcn: function(tcn) {
                return Registrations.query({ state: 'Active', tcn: tcn }).$promise;
            }
$httpBackend.expectGET('/api/v1/registration?state=Active&tcn=1234');

知道这是怎么回事吗? 我还没有尝试过,失败的版本在外部测试执行时是否确实有效,但有人看到过类似的行为吗?
谢谢

最佳答案

问题是查询参数按字母顺序排列,因此如果您有 foo 作为参数,那么您的断言将是:

$httpBackend.expectGET('/api/v1/registration?foo=1234&state=Active');

这一切都会过去。相反,如果参数是 zoo 那么断言将是:

$httpBackend.expectGET('/api/v1/registration?state=Active&zoo=1234');

这就是为什么您必须将 tcn 放在 state 参数之后,正如您在问题中指出的那样。

关于AngularJS 与 $resource 和 $httpBackend 的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24673323/

相关文章:

javascript - 您可以在创建时将参数传递给 AngularJS Controller 吗?

angularjs - Spring Security 实现最好没有 Spring Boot

javascript - 当我需要时, Angular promise 无法解决

unit-testing - Angular 2 单元测试错误 : Cannot resolve all parameters for 'RequestOptions'

angularjs - jasmine 遇到声明异常

angularjs - 尝试测试通用 angularjs $resource 服务时出现未知提供程序错误

javascript - 从 Angular js中的另一个ng-app调用方法

javascript - Jasmine StubRequest 未发送传递的字符串

angularjs - 错误状态代码未被捕获

javascript - 在 Angular-Resource 的帮助下将值插入 db.json