使用Jasmine单元测试模拟AngularJS Web服务

时间:2016-07-21 07:41:03

标签: angularjs unit-testing

我想使用Jamine来模拟我的Angular JS方法。我的代码是: -

<script type="text/javascript">

var app = angular.module('mymodulee', []);
   app.controller('mycontroller', function ($scope, $http, $log) {
    $scope.ButtonClick = function (Id) {

        var response = $http({
            method: "get",
            url: http://localhost:8080/Access/Tasks.DefectManagement/Services/Services.asmx/GetEligibilityDetails",
            params: {
                CovId: Id
            }

        });
        return response;
    }
});

我的茉莉花测试案例是: -

    it('EligibilityDetails', function () {

    var myserv, httpBackend;

    inject(function ($httpBackend, _myserv_) {
        myserv = _myserv_;
        httpBackend = $httpBackend;
    });



afterEach(function () {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
});
    var $scope = {};
    var controller = $controller('PatientDefectManagementCtrl', { $scope: $scope });

    var returnData = {};
    httpBackend.expectGET("http://localhost:8080/Access/Tasks.DefectManagement/Services/Services.asmx/GetEligibilityDetails").respond(returnData);

    var returnedPromise = myserv.get(3904142);

    var result;
    returnedPromise.then(function (response) {
        result = response.data;
    });

    httpBackend.flush();

    expect(result).toEqual(returnData);



});

但是它给出了一个错误。任何人都可以告诉我应该在我的代码中做出哪些更改,以便我可以使用Jasmine Unit测试来运行测试用例。

请帮忙。

由于

1 个答案:

答案 0 :(得分:0)

 describe('test',function(){
 afterEach(function () {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();});
 var myserv, httpBackend;
beforeEach(inject(function(_$httpBackend_,_myserv__){
myserv = _myserv_;
httpBackend = $httpBackend;});
it('EligibilityDetails', function () {
var $scope = {};
var controller = $controller('PatientDefectManagementCtrl', { $scope: $scope });
var returnData = {};
httpBackend.expectGET("http://localhost:8080/Access/Tasks.DefectManagement/Services/Services.asmx/GetEligibilityDetails").respond(returnData);

var returnedPromise = myserv.get(3904142);

var result;
returnedPromise.then(function (response) {
    result = response.data;
});

httpBackend.flush();

expect(result).toEqual(returnData);});});