角度单位测试http请求问题

时间:2015-02-10 22:35:04

标签: javascript angularjs unit-testing jasmine

我正在尝试为我的http请求编写单元测试

在我的控制器中,我有类似

的东西
     $scope.test1 = function(url) {
         productFactory.getProduct(url)
             .then(function(products){
                 $scope.result = products;
              })
    } 

在我的单位工厂文件

    angular.module('myApp').factory('productFactory', function($http) {
        var factoryObj = {};
        factoryObj.getProduct = function(url) {
            return http.get('/product/' + url)
        }
        return factoryObj
    })

在我的单元测试中,我不确定如何编写测试因为url是动态的

describe('test here', function () {
var testCtrl, scope, httpBackend, mockFactory;

// Initialize the controller and a mock scope
beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_,  _productFactory_) {
    scope = _$rootScope_.$new();
    httpBackend = _$httpBackend_;
    mockFactory = _productFactory_;

    testCtrl = _$controller_('testCtrl', {
        $scope: scope
    });


// the url is dynamic so I am not sure what to write here.

   var url = 12345 <----dynamic product id
   httpBackend.whenGet('/product/' + url).response({'name':'product1'}) 
   var promise = mockFactory.getProduct('/product/' + url);
   promise.then(function (prod) {
       var products = prod;
   });
   $httpBackend.flush();
   expect(products).toBeTruthy();
}));

当我进行测试时,我得到了

Error: Unexpected request: GET /product/undefined
Expected GET /product/12345

我不知道如何在我的情况下写一个http请求。任何人都可以帮我吗?谢谢!

1 个答案:

答案 0 :(得分:1)

您似乎想要测试productFactory而不是控制器。我能看到的唯一测试是确保发出适当的HTTP请求。

describe('productFactory test', function() {
    beforeEach(module('myApp'));

    it('getProduct requests /product/:id', inject(function($httpBackend, productFactory) {
        var id = 123;
        $httpBackend.expectGET('/product/' + id);

        productFactory.getProduct(id);
        $httpBackend.flush();
    }));
});

此外,您在productFactory.getProduct中输入错字。它应该是$http.get,而不是http.get


假设您的工厂使用 cookie 服务来获取ID。像这样......

.factory('productFactory', function($http, cookieService) {
    return {
        getProduct: function() {
            return $http.get('/product/' + cookieService.getProductid());
        }
    };
});

然后你会像这样测试它(假设茉莉花v2)......

describe('...', function() {
    var cookieService;

    beforeEach(module('myApp', function($provide) {
        $provide.value('cookieService',
            cookieService = jasmine.createSpyObj('cookieService', ['getProductId']));
    });

    it('...', inject(function($httpBackend, productFactory) {
        cookieService.getProductId.and.returnValue(123);
        $httpBackend.expectGET('/product/123');

        productFactory.getProduct();
        expect(cookieService.getProductId).toHaveBeenCalled();

        $httpBackend.flush();
    }));
});