简体   繁体   中英

How to test a http request in my case

I am trying to test a rootscope http request in my case

I have something like

mainCont file

$rootScope.testLoad = $http.get('/api/testapi/product');

TestCont file

$rootScope.testLoad.success(function(product){
    console.log(product)
})

Test file

describe('test', function () {
    var $httpBackend, $rootScope,  scope, mainCont, testCont;

    beforeEach(module('myApp'));

    beforeEach(inject(function (_$controller_, _$httpBackend_, _$rootScope_) {
        scope = _$rootScope_.$new();
        $rootScope = _$rootScope_;
        $httpBackend = _$httpBackend_;

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

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

    describe('test http request', function() {
        it('should check if the api is called', function() {       
            $httpBackend.expectGET('/api/testapi/product').respond(200);
            //I am not sure how to test the call in testCont file.  
        })
    })
});

I am not sure how to test the call in the testCont because when I run the test, I got an error saying

TypeError: 'undefined' is not an object (evaluating '$rootScope.testLoad.success')

Can anyone help me to fix this issue? Thanks a lot!

You've defined testLoad as a function, so you need to call it by adding parentheses. Change your code to

$rootScope.testLoad().success(function(product){
    console.log(product)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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