如何注入$ http服务

时间:2017-06-02 12:16:54

标签: angularjs jasmine karma-runner

我是angular.js的新手。但我想用一些单元测试编写代码。 如何在karma / jasmine中注入并测试$ http get方法? 下面的代码似乎不起作用。我使用的是Angular 1.4.7。

app.js

describe('Controllers', function(){ //describe your object type

var scope
var $http, $q;

beforeEach(module('MyApp')); //load module

beforeEach(inject(function(_$http_, _$q_) {
      $http = _$http_;
      $q = _$q_;
}));

describe('myctrl',function(){ //describe your app name

    beforeEach(inject(function($controller, $rootScope){ //instantiate controller using $controller service

        scope = $rootScope.$new
        myctrl = $controller('myctrl',{$scope: scope, $http: $http});

    }));


    it('Message should be ok', function(){  //write tests
        expect(scope.messge).toBe('ok'); //pass
    });

});       

});

app.specs.js

infile = open("new.csv", "r")
data = []
for line in infile:
    cols = line.split(",")
    Oposition = cols[0]
    Winner = cols[1]
    Margin = cols[2]
    Ground = cols[3]
    Year = cols[4]
    pair = (Oposition, Winner, Margin, Ground, Year)
    data.append(pair)
infile.close()

1 个答案:

答案 0 :(得分:0)

使用$ httpBackend模拟HTTP调用。阅读this