在测试中重新初始化angularjs

时间:2014-04-19 03:41:57

标签: angularjs unit-testing

我正在为一项具有一定持久性的服务编写一些anuglarjs测试。我想:

  1. 注入服务
  2. 填写一些数据
  3. 重新初始化角度(以便重新启动服务的单身人员"
  4. 测试该服务是否包含我在步骤#2中放入的内容
  5. 我认为我能够在我的测试中调用angular.mock.module来重新初始化它,但这并不好,它只会抛出我们无法配置的错误注射器创建后。

    测试显示:

    describe('commBuffer', function () {
      beforeEach(angular.mock.module('step'));
    
      it('persists buffers across sessions',inject(function(commBuffer,connectivity) {
        connectivity.isOnline = false;
        commBuffer.issue({ method: 'GET', url: '/api/data' });
        commBuffer.bufferSize.should.eql(1);
        angular.mock.module('step'); //How do I wipe out the current angular session and re-init it?
    
        //Does the commBuffer persist it's buffer between sessions?
        commBuffer.bufferSize.should.eql(1);
      }));
    
    });
    

    知道如何在测试中重新初始化anguarjs吗?

1 个答案:

答案 0 :(得分:0)

AFAIK,您无法在测试中重新初始化Angular。但...

...你可能试图测试太多。无论commBuffer使用哪种持久层,您都应该在将其注入测试之前进行模拟,并测试commBuffer是否按预期使用它。然后,您可以有效地相信HTML5存储会像您期望的那样持续存在。 (还有更多东西用于E2E /集成测试)

假设您正在使用HTML5存储空间,您可以通过$window.localStorage直接访问该存储空间。您可以按照以下方式对其进行模拟(只是一个示例,还有其他模式,并且都是未经测试的。)

describe('commBuffer', function () {
  var localStorageMock, commBuffer, connectivity;

  beforeEach(angular.mock.module('step'));

  beforeEach(function() {
    // Clear before every test
    localStorageMock = {
      getItem: function(key) {},
      setItem: function(key, value) {}
    };
  });

  beforeEach(module(function($provide) {
    $provide.value('$window', {
      localStorage: localStorageMock
    });
  }));

  // You'll have to change the following for
  // the exact behaviour of commBuffer / bufferSize
  describe('on initialisation', function() {

    beforeEach(function() {
      // Your test buffer data
      spyOn(localStorage, 'getItem').andReturn('test-data');
    });

    beforeEach(inject(function(_commBuffer_, _connectivity_) {
      commBuffer = _commBuffer_;
      connectivity = _connectivity_;
    });

    it('gets the buffer from storage', function() {
      // Whatever the test needs to be to check the buffer
      // was retrieved from the mock storage service
      commBuffer.bufferSize.should.eql(1);
    });   
  });      
});

以上是一个简单的例子。根据{{​​1}}的作用,您可能需要为服务设置更复杂的间谍/模拟。