简体   繁体   中英

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

I have read a lot of articles and I still don't understand how to create it.

There is a module (“A”) that has service (“B”) that has function (“C”). The function is using another function (“E”) in other module(“D”). I want to test the behavior of the function (“C”), with different answers from function (“E”), [true, False, etc...]

Example:

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

I built the app with Yeoman Angular generator

Thank you

Assuming everything lives under one module say 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;
  });

Unit Test:

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();

    });
  });
});

Lets say that it lives in a different module - module 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;
      });

Unit Tests:

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();

    });
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM