AngularJS:如何使用内部$ http调用测试功能?

时间:2018-09-20 13:11:47

标签: angularjs unit-testing jasmine karma-jasmine

假设我有这样的代码:

getFromLocation

有什么方法可以用... $scope.articles = [{id: 1}, {id: 2}]; $scope.openArticle = (artId) => { ... const article = ...; $http.post(`url`, `body`).then(() => { article.opened = true; }, () => {}); }; 进行测试吗?

例如,我尝试这样做:

jasmine

1 个答案:

答案 0 :(得分:1)

让我展示一个使用茉莉花和$ httpBackend的示例。

    import moduleTest from '../index';

    import dataJsonTest from './dataJsonTest.json';

    describe('Controller Test', function() {
    let controller;
    let httpBackend;
    let rootScope;
    let scope;

    beforeEach(angular.mock.module(moduleTest));

    beforeEach(angular.mock.inject(($controller, $httpBackend, $rootScope) => {
        controller = $controller;
        httpBackend = $httpBackend;
        rootScope = $rootScope;
        scope = $rootScope.$new();
        setHttpExpected();
    }));

    afterEach(() => {
        /*  Verifies that all of the requests defined via the expect api were made. 
            If any of the requests were not made, verifyNoOutstandingExpectation throws an exception.

            Typically, you would call this method following each test case that asserts requests using an "afterEach" clause.
        */
        httpBackend.verifyNoOutstandingExpectation();
        /*
            Verifies that there are no outstanding requests that need to be flushed.

            Typically, you would call this method following each test case that asserts requests using an "afterEach" clause.        
         */
        httpBackend.verifyNoOutstandingRequest();
    });

    function setHttpExpected() {
        let data = dataJsonTest;

        httpBackend.when('GET', '/api/model', data, undefined)
            .respond(function(method, url, data, headers){
                return [204, data, {}];
            });            
    }

    it('Test list return', () => {
        let ctrl = controller('myController', {$scope: scope, $rootScope: rootScope});
        executeRequestSynchronously(httpBackend);

        expect(ctrl.data.length).toBe(3);
    });    

    /**
     * https://docs.angularjs.org/api/ngMock/service/$httpBackend
     * 
     * After flush is possible catch the values and expecs with jasmine
     */
    var executeRequestSynchronously = (httpBackend) => httpBackend.flush();
});