如何在AngularJS中使用Jasmine监听模拟服务的更改

时间:2016-12-26 17:34:33

标签: angularjs unit-testing jasmine

我正在尝试更改模拟服务中方法的返回值,但永远不会调用新方法。

代码:

describe('Test 1', function() {
  var ctrl, scope, mySrvMock;

  beforeEach(function() {
    mySrvMock = {
      method: function() {
        return 'value';
      }
    }
  });

  beforeEach(function() {
    module('app');
    inject(function($rootScope, $controller) {
      scope = $rootScope.$new();
      ctrl = $controller('mainCtrl', {
        $scop: scope,
        mySrv: mySrvMock
      });
    });
  });

  it('should return value', function() {
    expect(scope.callToMethod).toBe('value') // Pass
  });

  describe('Test 1.1', function() {
    beforeEach(function() {
      mySrvMock.method = function() {
        return 'different value';
      };
    });

    it('should return different value', function() {
      expect(scope.callToMethod).toBe('different value') // Fail (Expected 'value' to be 'different value')
    });
  });
});

有一种方法可以收听模拟服务的变化吗?

1 个答案:

答案 0 :(得分:1)

在每个it()之前初始化控制器

    describe('Test 1', function() {
  var ctrl, scope, mySrvMock, controllerFactory;

  beforeEach(function() {
    mySrvMock = {
      method: function() {
        return 'value';
      }
    }
  });

  beforeEach(function() {
    module('app');
    inject(function($rootScope, $controller) {
      scope = $rootScope.$new();
      controllerFactory = $controller.bind(this, 'mainCtrl',{
        $scop: scope,
        mySrv: mySrvMock
      }); 
      ctrl = controllerFactory();
    });
  });
describe('Test 2.1', function() {
    beforeEach(function() {
      ctrl = controllerFactory();
    });

  it('should return value', function() {
    expect(scope.callToMethod).toBe('value') // Pass
  });

});
  describe('Test 1.1', function() {
    beforeEach(function() {
      mySrvMock.method = function() {
        return 'different value';
      };
      ctrl = controllerFactory();
    });

    it('should return different value', function() {
      expect(scope.callToMethod).toBe('different value') // Fail (Expected 'value' to be 'different value')
    });
  });
});