Angularjs $ http模拟问题

时间:2013-05-22 22:35:03

标签: angularjs unit-testing debugging karma-runner

我需要一些帮助格式化我的单元测试以获得来自testacular / karma的预期结果

beforeEach( inject( function( customService, $httpBackend ){            
         service = customService;
         $http = $httpBackend
;}))

it('should make a default call upon initialization',function(){

var modalObj = {
                 "id": null,
                 "contentId": null,
                 "isActive":false,
                 "websiteId":2000,
                 "createdByUserName":"haselton",
                 "text":"another micro",
                 "tags":[],
                 "something random":null,
                 "something else":3
              },
              requestObj = {"isActive":false,"tags":[],"websiteId":2000,"createdByUserName":"haselton","text":"another micro"},
            mbObj = {};


         $http.whenPOST('/url/of/call', [requestObj]).respond(
             {
                 "id": 40,
                 "contentId": null,
                 "isActive": false,
                 "creationDate": "05/22/2013 14:24:14 PDT",
                 "lastModifiedDate": "05/22/2013 14:24:14 PDT",
                 "lastModifiedStatusDate": null,
                 "websiteId": 2000,
                 "createdByUserName": "haselton",
                 "text": "another micro",
                 "tags": []
             }
         );

然后我有一个服务产生调用并返回一个promise。以下是测试的其余部分:

         mbObj = service.createEntry(modalObj); // returns a promise
         mbObj.then(function(data){
             console.log(data);
             expect( angular.isNumber(data.id)).toBe(true);
             expect(data.isActive).toBe(false);
             expect(data.tags).toBe( 0 );
             expect(data.websiteId).toBe(2000);
             expect(data.createdByUserName).toBe("haselton");
             expect(data.text).toBe("another micro");
         }); 

         $http.flush();

});

而不是传递,履行承诺内的console.log会注销Angular Resources。这是一个屏幕截图: enter image description here

关于我在这里做错了什么的想法?谢谢!

1 个答案:

答案 0 :(得分:0)

data请求解析的modalObj参数是一个数组,因此请使用下标来获取实际数据:

console.log(data[0], data[1], data[2], data[3] , data[4], data[5], data[6], data[7], data[8], data[9]);