首页 > 解决方案 > AngularJS:带有 $http 调用的测试方法引发错误

问题描述

我在 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);
        });
    });
});

但它只是在没有任何解释的情况下引发错误:什么和哪里错了

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

标签: angularjsjasminekarma-jasmine

解决方案


推荐阅读