【问题标题】:httpBackend.expectPUT not working in angularjs factory unit testhttpBackend.expectPUT 在 angularjs 工厂单元测试中不起作用
【发布时间】:2016-04-08 02:48:14
【问题描述】:

以下是我尝试进行单元测试的示例服务:

    angular.module('sampleModule')
        .factory('sampleService', sampleService);

    sampleService.$inject = ['$http'];

    function sampleService($http) {
        var endpoint = "http://localhost:8088/api/customers/"
        return {
            getData: function(id){
                return $http({
                    method: 'GET',
                    url: endpoint + id
                });
            },
            updateData: function(id, requestBodyObject){
                return $http({
                    method: 'PUT',
                    url: endpoint + id,
                    data: requestBodyObject

                });
            }
        };
    }

以下是我必须测试上述服务的示例规范。但是它的抛出错误

    describe('Sample Service', function(){

        var service, httpBackend;

        beforeEach(function(){
            angular.mock.module('sampleModule');

            angular.mock.inject(function(_sampleService_, $httpBackend){
                service = _sampleService_;
                httpBackend = $httpBackend;
            });
        });


        it('updateAdvisorAttributesData should return response on valid acctNumber', function(){
            var response = {};
            var errResponse = {};
            var id = 1234;
            var requestBody = {
              '1': 'one'
            };
            var endpoint = "http://localhost:8088/api/customers/"

            httpBackend.expectPUT(endpoint + id, requestBody).respond(200, {'key': 'value'});

            service.updateData(id).then(function(result){
                response = result;
            },function(error){
                errResponse = error;
            });

            httpBackend.flush();
            expect(response.status).toBe(200);
            expect(response.data).toEqual({'key': 'value'});

        });
    });

执行规范时出错:

    Error: Expected PUT http://localhost:8088/biga/advisors/1234 with different data
    EXPECTED: {"1":"one"}
    GOT:      undefined

同样的方法适用于 httpBackend.expectGET()。然而,它的 PUT 失败了。为什么会失败?我该如何解决?

【问题讨论】:

    标签: angularjs jasmine httpbackend angular-mock


    【解决方案1】:

    你在做测试时并没有通过身体。

    变化:

    service.updateData(id).then(function(result){
    

    到:

    service.updateData(id, requestBody).then(function(result){
    

    【讨论】:

      猜你喜欢
      • 2017-10-07
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多