9

Angular の$httpBackend サービスをexpectGET使用すると、expectPOST、 など (または のみ)を含む HTTP リクエストを期待できますexpect

「コントローラーは、(これらの条件下で) このエンドポイントにリクエストを送信してはならない」というテストをどのように作成すればよいでしょうか?

私は次のようなことを考えていました:

$httpBackend.when('/forbidden/endpoint').respond(function() {
  throw Error("Shouldn't be making a request to /forbidden/endpoint!");
});

それは私には少しハックに思えますが、それが通常のやり方であれば問題ありません。(しかし、私はそれを疑います。)

4

4 に答える 4

12

私は同じ問題につまずいた。

解決策は、応答としてコールバック関数を使用することであり、内部でできることexpect(true).toBe(false)、または私の意見では、もう少し美しいものを使用することです。

it ('should not trigger HTTP request', function() {
    var forbiddenCallTriggered = false;
    $httpBackend
      .when('/forbidden/endpoint')
      .respond(function() {
        forbiddenCallTriggered = true;
        return [400, ''];
      });

    // do whatever you need to call.

    $rootScope.$digest();
    $httpBackend.flush();

    // Let test fail when request was triggered.
    expect(forbiddenCallTriggered).toBe(false);
  });
于 2014-09-10T11:19:19.720 に答える
5

このようなシナリオでは、Jasmine の spyOn()関数をよく使用します。$http$resource、またはカスタム サービスの関数をスパイできます (myServiceThatUsesHTTP以下のように)。

spyOn(myServiceThatUsesHTTP, 'query');
// test, then verify:
expect(myServiceThatUsesHTTP.query).not.toHaveBeenCalled();
// or
expect(myServiceThatUsesHTTP.query.callCount).toBe(0);

関数をspyOn()使用すると、元の関数が置き換えられます。元の関数のコードは実行されませんが、これは良いことも悪いこともあります (テストのために何をする必要があるかによって異なります)。

たとえば、$promise$http または $resource が返すオブジェクトが必要な場合は、次のようにします。

spyOn($http, '$get').andCallThrough(); 
于 2014-03-14T16:09:15.370 に答える
2

$httpBackend.flush()1 つの解決策は、フラッシュするものが何もないはずなので、 が例外をスローするかどうかを確認することです。

beforeEach(function() {
   $httpBackend.whenGET('/forbidden/endpoint');
   ...
   // call service method under test (that should not make $http call)
});

it('Should not call the endpoint', function() {
    expect($httpBackend.flush).toThrow();
});

注意すべき重要な点:実際には呼び出しが行われるとは想定していないため、 ではwhenなく andを使用します。expectまた、呼び出しがないため$httpBackend.flush()、例外がスローされます。フラッシュする保留中の要求はありません。

于 2017-01-10T12:57:38.420 に答える
0

$httpBackend$httpこのテストでは呼び出しが行われないため、適用されません。

$http代わりに、テストに注入してからspyOn() $http直接:

beforeEach(fn () { 
  inject(function ($injector) {
    this.service = $injector.get('serviceOrControllerOrDirectiveBeingTested');
    this.$http = $injector.get('$http');
  }
});

その後

it('should ...', fn() {
  spyOn(this.$http, 'get');
  this.service.methodThatTriggersTheHttpCall();
  expect(this.$http.get).not.toHaveBeenCalled();
});
于 2015-11-13T17:48:13.493 に答える