简体   繁体   English

如何测试http请求

[英]how to test http request

i am new to angularjs ,i have done with my first angular app now i want to test them as well in my app i get some Json data from url and populate in a list i want to test http request but my test fails here is my controllerspec: 我是angularjs的新手,我已经完成了我的第一个angular应用程序,现在我也想在我的应用程序中对其进行测试。我从url中获取了一些Json数据,并在列表中填充了我想测试http请求的内容,但是我的测试失败了controllerspec:

describe('myAppCtrl', function() {
    var scope, controller, httpBackend;


    beforeEach(module('myApp'));
    beforeEach(inject(function($rootScope, $controller, $httpBackend) {
        scope = $rootScope;
        controller = $controller;
        httpBackend = $httpBackend;
    }));

    it('should populate the reddit data when the HTTP request succeeds', function() {

        httpBackend.when('GET','https://www.reddit.com/r/worldnews/new.json').respond({names});

        controller('myAppCtrl', {'$scope': scope });
        httpBackend.flush();
        scope.$apply();

        expect(scope.names.children.length).toEqual(25);

    });
    it('should show the number of items in list',function() {
        var data = $('#title');
        expect(data).toBeTruthy();
        //expect(1).toBe(1);
    }); 


});

Here is my app in plunkr 这是我在plunkr中的应用

To make it fully testable you need some fixes in your controller which are as follows. 为了使其完全可测试,您需要在控制器中进行以下修复。

 var app = angular.module('myApp', []);
 app.controller("myAppCtrl", function ($scope, $http) {
     $scope.names = []
     //watch sortBy
     $scope.$watch(function () {
         return $scope.sortExpression
     }, function (newSort) {
         $scope.sortBy = 'data.' + $scope.sortExpression
     })

     $scope.init = function(){
        return  $http.get("https://www.reddit.com/r/worldnews/new.json")
         .success(function (response) {
                 $scope.names = response.data.children;
                 return response;
          })
       }  
      $scope.init();  
 });

**testSpec.js**


    describe('myAppCtrl', function() {
        var scope, controller, httpBackend;
        var data = {
    "kind": "Listing",
    "data": {
        "modhash": "",
        "children": [{
            "kind": "t3",
            "data": {
                "domain": "theguardian.com",
                "banned_by": null,
                "media_embed": {},
                "subreddit": "worldnews",
                "selftext_html": null,
                "selftext": "",
                "likes": null,
                "suggested_sort": null,
                "user_reports": [],
                "secure_media": null,
                "link_flair_text": null,
                "id": "3ef7lv",
                "from_kind": null,
                "gilded": 0,
                "archived": false,
                "clicked": false,
                "report_reasons": null,
                "author": "anutensil",
                "media": null,
                "score": 4,
                "approved_by": null,
                "over_18": false,
                "hidden": false,
                "num_comments": 0,
                "thumbnail": "",
                "subreddit_id": "t5_2qh13",
                "edited": false,
                "link_flair_css_class": null,
                "author_flair_css_class": null,
                "downs": 0,
                "secure_media_embed": {},
                "saved": false,
                "removal_reason": null,
                "stickied": false,
                "from": null,
                "is_self": false,
                "from_id": null,
                "permalink": "/r/worldnews/comments/3ef7lv/beekilling_pesticides_quietly_permitted_by_the_uk/",
                "name": "t3_3ef7lv",
                "created": 1437752870.0,
                "url": "http://www.theguardian.com/environment/2015/jul/23/bee-killing-pesticides-quietly-permitted-by-the-uk-government",
                "author_flair_text": null,
                "title": "Bee-killing pesticides quietly permitted by the UK govt",
                "created_utc": 1437724070.0,
                "distinguished": null,
                "mod_reports": [],
                "visited": false,
                "num_reports": null,
                "ups": 4
            }
        }, {
            "kind": "t3",
            "data": {
                "domain": "m.sputniknews.com",
                "banned_by": null,
                "media_embed": {},
                "subreddit": "worldnews",
                "selftext_html": null,
                "selftext": "",
                "likes": null,
                "suggested_sort": null,
                "user_reports": [],
                "secure_media": null,
                "link_flair_text": "Ukraine/Russia",
                "id": "3ef6q4",
                "from_kind": null,
                "gilded": 0,
                "archived": false,
                "clicked": false,
                "report_reasons": null,
                "author": "dexter93",
                "media": null,
                "score": 0,
                "approved_by": null,
                "over_18": false,
                "hidden": false,
                "num_comments": 2,
                "thumbnail": "",
                "subreddit_id": "t5_2qh13",
                "edited": false,
                "link_flair_css_class": "ukrassia",
                "author_flair_css_class": null,
                "downs": 0,
                "secure_media_embed": {},
                "saved": false,
                "removal_reason": null,
                "stickied": false,
                "from": null,
                "is_self": false,
                "from_id": null,
                "permalink": "/r/worldnews/comments/3ef6q4/french_lawmakers_surprised_by_happy_citizens_in/",
                "name": "t3_3ef6q4",
                "created": 1437752114.0,
                "url": "http://m.sputniknews.com/russia/20150724/1024986748.html",
                "author_flair_text": null,
                "title": "French Lawmakers Surprised by \u2018Happy\u2019 Citizens in Crimea\u2019s Yalta / Sputnik International",
                "created_utc": 1437723314.0,
                "distinguished": null,
                "mod_reports": [],
                "visited": false,
                "num_reports": null,
                "ups": 0
            }

        }],
        "after": "t3_3eeqtg",
        "before": null
    }
}



    beforeEach(module('myApp'));
    beforeEach(inject(function($rootScope, $controller, $httpBackend) {
        scope = $rootScope;
        controller = $controller;
        httpBackend = $httpBackend;
    }));

    it('should populate the reddit data when the HTTP request succeeds', function(done) {

        httpBackend.when('GET','https://www.reddit.com/r/worldnews/new.json').respond({data:data});

        controller('myAppCtrl', {'$scope': scope });
        httpBackend.flush();
        scope.$apply();

        scope.init().then(function(resp){
            expect(resp.data).not.toBeNull();
               done();
        });

    });
    it('should show the number of items in list',function() {
        var data = $('#title');
        expect(data).toBeTruthy();
        //expect(1).toBe(1);
    }); 


    });

check out plunker 退房矮人

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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