如何让单元测试工作?

时间:2014-11-12 01:48:57

标签: angularjs unit-testing jasmine karma-runner

如何让这个单元测试工作?

控制器:

var app = angular.module('plunker', []);

app.controller('myCtrl', function ($http, $scope) {
    $http.get('https://api.github.com/users/jasonmore').then(function (data) {
            $scope.myData = data;
        },
        function (err) {
            console.log(err);
        }
    );

})

和规范:

describe('mocking service http call', function () {
    beforeEach(module('plunker'));

    var myCtrl, $scope;


    describe('with httpBackend', function () {
        beforeEach(inject(function ($controller, $rootScope, $httpBackend) {
            $scope = $rootScope.$new();

            $httpBackend.when('GET', 'https://api.github.com/users/jasonmore')
                .respond({data:{}});

            myCtrl = $controller('myCtrl', { $scope: $scope });
            $httpBackend.flush();
        }));

        it('should set data ', function () {
            expect($scope.myData).toEqual({data:{}});
        });
    });
});

如何修复此错误信息:

Expected { data : { data : { } }, status : 200, headers : Function, config : { method : 'GET', transformRequest : [ Function ], transformResponse : [ Function ], url : 'https://api.github.com/users/jasonmore', headers : { Accept : 'application/json, text/plain, */*' } }, statusText : '' } to equal { data : { } }.

这是我的傻瓜:http://plnkr.co/edit/8qu3x9DUTa05fggheclP?p=preview

1 个答案:

答案 0 :(得分:0)

当您使用$http.then而不是success时,响应包含一个具有属性的对象

数据,状态,标题,配置

因此回调分配不正确。它应该是:

  $http.get('https://api.github.com/users/jasonmore').then(function (data) {
            $scope.myData = data.data;  //this needs to be data.data
        },
        function (err) {
            console.log(err);
        }
    );