我有以下 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/