AngularJS: как протестировать функции с внутренними вызовами $ http? - PullRequest
0 голосов
/ 20 сентября 2018

Допустим, у меня есть такой код:

...

$scope.articles = [{id: 1}, {id: 2}];

$scope.openArticle = (artId) => {
    ...

    const article = ...;

    $http.post(`url`, `body`).then(() => {
        article.opened = true;
    }, () => {});
};

Есть ли способ проверить это с помощью jasmine?

, например, я пытаюсь так:

...

it('should open article', () => {
        expect($scope.articles).toBeDefined();

        $scope.toggleFeature(1);

        expect($scope.articles[0].opened).toBe(true);
});

...

but sure, it won't work this way - I have a promisse inside
I can't change my code to return anything...
so: is it possible to test such function somehow?

1 Ответ

0 голосов
/ 20 сентября 2018

Позвольте мне показать пример с жасмином и $ 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();
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...