【问题标题】:how to get unit test working?如何让单元测试工作?
【发布时间】:2014-11-12 01:48:57
【问题描述】:

我怎样才能让这个单元测试工作?

控制器:

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 : { } }.

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

【问题讨论】:

    标签: angularjs unit-testing jasmine karma-runner


    【解决方案1】:

    当您使用 $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);
            }
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-19
      • 2017-09-20
      相关资源
      最近更新 更多