簡體   English   中英

如何創建Karma / Jasmine單元測試以檢查依賴於其他模塊的Angular服務

[英]How to create a Karma/Jasmine unit tests to check Angular service that depend on other module

我已經閱讀了很多文章,但我仍然不知道如何創建它。

有一個模塊(“ A”)具有服務(“ B”)且具有功能(“ C”)。 該功能正在其他模塊(“ D”)中使用另一個功能(“ E”)。 我想測試功能(“ C”)的行為,並從功能(“ E”),[true,False等...]獲得不同答案

例:

angular.module('A',[]) // or angular.module('A',['D']) .service('B', function(){ this.C = function() { return !DE() ; };

我使用Yeoman Angular生成器構建了該應用程序

謝謝

假設所有內容都在一個模塊下,則說A。

angular.module('A',[])
  .service('B', function(D) { // Using Dependency Injection we inject service D here
    this.C = function() {
      return !D.E();
    }
    return this;
  })
  .service('D', function() {
    this.E = function() { return false; };
    return this;
  });

單元測試:

describe('Unit Test for the Service B', function() {

  var B, D;  

  beforeEach(function() {
    module('A');
  });

  beforeEach(inject(function(_B_, _D_) {
    B = _B_;
    D = _D_;
  }));

  describe('Functionality of method C', function() {

    it('should negate the returned value of the method E in service D', function() {
      var E = D.E();
      var C = B.C();
      expect(E).toBeFalsy();
      expect(C).toBeTruthy();

    });
  });
});

假設它位於另一個模塊-模塊Z中。

angular.module('A',['Z']) // Now we include the module Z here
      .service('B', function(D) { // and again using Dependency Injection we can inject service D here.
        this.C = function() {
          return !D.E();
        }
        return this;
      });
angular.module('Z', [])
      .service('D', function() {
        this.E = function() { return false; };
        return this;
      });

單元測試:

describe('Unit Test for the Service B', function() {

  var B, D;  

  beforeEach(function() {
    module('A');
    module('Z');
  });

  beforeEach(inject(function(_B_, _D_) {
    B = _B_;
    D = _D_;
  }));

  describe('Functionality of method C', function() {

    it('should negate the returned value of the method E in service D', function() {
      var E = D.E();
      var C = B.C();
      expect(E).toBeFalsy();
      expect(C).toBeTruthy();

    });
  });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM