简体   繁体   English

如何测试$ resource调用是否包含发出HTTP请求时的特定标头?

[英]How to test $resource calls if it contains specific headers on making http request?

I have this following factory. 我有以下工厂。

services.factory('Api', ['$resource', function ($resource) {

        return $resource(urlPath, {
            'action': 'get',
            'entity': 'Entity'
        }, {
          MakePost: {
            method: "POST",
            isArray: false,
            headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
            transformRequest: function(obj) {
              var str = [];

              for (var p in obj) {
                str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
              }

              return str.join("&");
            }
          }
        }
      );
    }]);

Now, i would like to test, when calling Api.MakePost({},{data: {}}, function () {}) the correct header data ie in this case 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' 现在,当调用Api.MakePost({},{data: {}}, function () {})时,我想测试正确的头数据,即在这种情况下为'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' is set correctly. 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'设置正确。 Is there away to test this scenario in angularjs, using $httpBackend, Jasmine and spies? 是否可以使用$ httpBackend,Jasmine和间谍在angularjs中测试此方案?

This can be tested in two different ways, with unit and functional tests. 可以通过两种不同的方式进行测试,包括单元测试和功能测试。

When compared with $http , $resource contains more moving parts, and it makes sense to stub it - at least for some tests. $http相比, $resource包含更多的活动部件,因此对它进行存根是有意义的-至少对于某些测试而言。

beforeEach(module('app'))
...
describe('$resource is stubbed in this block', () => {
  var resourceObjStub;
  var resourceFactoryStub;

  beforeEach(() => {
    resourceObjStub = jasmine.createSpyObj(['MakePost']);
    resourceFactoryStub = jasmine.createSpy().and.returnValue(resourceObjStub);

    module({ $resource: resourceFactoryStub });
  });

  it('...', inject((Api) => {
    expect(resourceFactoryStub).toHaveBeenCalledWith(
      ...
      {...},
      { MakePost: {
        headers: {...},
        transformRequest: jasmine.any(Function),
        ...
      } }
    );
    expect(Api).toBe(resourceObjStub);
  });
});

Then provided $resource arguments can be tested more thoroughly, eg transformRequest method can be reached with resourceFactoryStub.calls.first()[2].transformRequest and tested directly. 然后,可以对提供的$resource参数进行更彻底的测试,例如,可以使用resourceFactoryStub.calls.first()[2].transformRequest来访问transformRequest方法并直接进行测试。

Or the whole thing can be tested in another test with $httpBackend and real $resource . 或者可以使用$httpBackend和真实的$resource在另一个测试中测试整个事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM