6

Karma と Jasmine を使用して AngularJS アプリケーションを単体テストしようとしています。$httpサービスをモックしたい。そのために、$httpBackend メソッドを使用しています。以下は、テストしたいサービスです。

angular.module('MyModule').factory('MyService', function($http, $log, $parse, $q, $timeout, $filter, MyOtherService1, MyOtherService2){
var service = {};
   service.getSomething = function(id){
     return $http.get('/somePath/subpath/' + id);
   }
});

このサービスの単体テストは次のとおりです。

describe("myTest", function(){
    var myService, $httpBackend, scope, mockMyOtherService1, mockMyOtherService2;

    var myResponse =
    {
        foo:'bar'
    };

    beforeEach(module("MyModule"));

    beforeEach(inject(function(_MyService_, $injector){

        $httpBackend = $injector.get('$httpBackend');
        myService = _MyService_;
        scope = $injector.get('$rootScope').$new();
        mockMyOtherService1 = $injector.get('MyOtherService1');
        mockMyOtherService2 = $injector.get('MyOtherService2');

    }));

    beforeEach(function(){
        //To bypass dependent requests
        $httpBackend.whenGET(/\.html$/).respond(200,'');
    });

    //If I uncomment the below afterEach block, the same error is shown at next line.
    /*afterEach(function() {
         $httpBackend.verifyNoOutstandingExpectation();
         $httpBackend.verifyNoOutstandingRequest();
     });*/

    //This test passes successfully
    it("should check if service is instantiated", function () {
        expect(myService).toBeDefined();
    });

    //This test passes successfully
    it("should expect dependencies to be instantiated", function(){
        expect($httpBackend).toBeDefined();
    });

    //The problem is in this test
    it("should get the getSomething with the provided ID", function() {
        $httpBackend.whenGET('/somePath/subpath/my_123').respond(200,myResponse);            
        var deferredResponse = myService.getSomething('my_123');

        //The error is shown in next line.
        $httpBackend.flush();      

        //If I comment the $httpBackend.flush(), in the next line, the $$state in deferredResponse shows that the Object that I responded with is not set i.e. it does not matches the 'myResponse'.
        expect(deferredResponse).toEqual(myResponse);

    });
});

これは緊急の問題であり、できるだけ早く同じことについて助けが必要です. 私はあなたの答えにとても感謝しています。

4

3 に答える 3

1

問題は、サービスに挿入されていないにもかかわらず、スペック ファイルに $location を挿入する必要があったことです。注入後、すべてうまくいきました!これが同じ状況で立ち往生している人を助けることを願っています.

于 2015-12-14T15:15:26.627 に答える
1

あなたはあなたのサービスから約束を得るでしょう。したがって、テスト コードを次のように変更します。

//The problem is in this test
it("should get the getSomething with the provided ID", function (done) {
  $httpBackend.expectGET('/somePath/subpath/my_123').respond(200,myResponse);
  var deferredResponse = myService.getSomething('my_123');

  deferredResponse.then(function (value) {
    expect(value.data).toEqual(myResponse);
  }).finally(done);

  $httpBackend.flush();
});
于 2015-11-23T13:33:23.027 に答える