AngularJS:$ http调用的测试方法引发错误

时间:2018-11-21 08:44:14

标签: angularjs jasmine karma-jasmine

我在AngularJS中有这样的控制器:

  (angular => {
    'use strict';

    const component = {
        bindings: {
            fileLoaded: '&'
        },
        templateUrl:
            '/some-component/some-component.template.html',
        controller
    };

    function controller(SomeService) {
        const ctrl = this;

        ctrl.data = null;
        ctrl.isLoading = false;

        ctrl.saveIt = (data) => {
            ctrl.isUpdating = true;

            SomeService.setData(data).then(
                () => {
                    ctrl.isLoading = false;
                    ctrl.data = data;
                },
                () => {
                    ctrl.isLoading = false;
                });
        };
    }

    controller.$inject = [ 'SomeService' ];

    angular.module('myApp').component('someComponent', component);
})(window.angular);

然后我尝试编写这样的测试:

'use strict';

describe('someComponent Component', () => {
    let $componentController;
    let $rootScope = null;
    let $scope = null;
    let $httpBackend = null;
    let SomeService = null;

    beforeEach(module('myApp'));
    beforeEach(inject(function(_$componentController_, _$rootScope_, _$httpBackend_, _SomeService_) {
        $componentController = _$componentController_;
        $rootScope = _$rootScope_;
        $httpBackend = _$httpBackend_;
        SomeService = _SomeService_;

        $scope = $rootScope.$new();
    }));

    describe('method: saveIt', () => {
        it('call saveIt (POST)', () => {
            const ctrl = $componentController('someComponent', null, {});

            const data = { someData: 'someDataSomeData' };

            ctrl.saveIt(data);

            $httpBackend
                .expectPOST('/someURL')
                .respond(200, {});

            SomeService.setData(data)
                .then(() => {
                    ctrl.isLoading = false;
                    ctrl.data = data;
                })
                .catch(() => {
                    ctrl.isLoading = false;
                });

            $httpBackend.flush();

            expect(ctrl.data).not.toBe(null);
            expect(ctrl.isLoading).toBe(false);
        });
    });
});

但是它只是引发一个错误而没有任何解释:什么和哪里错了

如何调试和解决它?我做错了什么?

0 个答案:

没有答案