如何在每个业力/茉莉花测试文件的开头引导角度?

ngD*_*per 3 javascript unit-testing angularjs karma-jasmine

是否可以在每个测试文件的开头使用角度引导应用程序?而不是当前行为,在一系列测试开始时有app bootstrap,然后在所有测试文件中使用相同的实例(我们现在大约有600个测试~60个文件)?

我们之前有一些声明来处理清理工作并没有帮助.实际上,有时看起来有一些beforeEach语句完全没有明显的原因(测试运行器可能存在内存泄漏).

因此,我想采取的路线是让每个测试文件引导角度应用程序,以便状态完全重置,而不是重用具有由不同测试设置的状态的依赖注入(即服务).

pes*_*ior 5

您无需为测试引导应用程序.这就是我们拥有的原因angular-mock.随着angular.module('app.module')我们加载我们需要为我们的测试模块和该模块包含了我们要测试的组件.由于angular-mock不是内存泄漏的原因,因此可能有几个原因.内存泄漏的最常见原因之一是茉莉本身和我们通常编写测试的方式.我们在测试中注入的依赖项使用的变量在describe范围内定义,并且在测试完成时无法由GC收集.这是因为it块中的那些变量的引用不能被垃圾收集,因为变量仍然存在于测试树的其他范围内.另一个问题可能是在每次测试后也应该清理的编译元素.所以你可能需要清理以下内容:

  • 使用$ compile进行测试指令时编译的元素
  • describe函数范围内的所有变量

你可以这样做:

describe('testSuite', function () {
    var suite = {};

    beforeEach(module('app'));

    beforeEach(inject(function ($rootScope, $compile, heavyLoad) {
      suite.$rootScope = $rootScope;
      suite.$compile = $compile;
      suite.heavyLoad = heavyLoad;
      suite.$scope = $rootScope.$new();

      spyOn(suite.heavyLoad, 'getHeavyString').and.callThrough();
      spyOn(suite.heavyLoad, 'getHeavyObject').and.callThrough();
      spyOn(suite.heavyLoad, 'getHeavyList').and.callThrough();
    }));

    // NOTE: cleanup
    afterEach(function () {
      // NOTE: prevents DOM elements leak
      suite.element.remove();
    });
    afterAll(function () {
      // NOTE: prevents memory leaks because of JavaScript closures created for 
      // jasmine syntax (beforeEach, afterEach, beforeAll, afterAll, it..).
      suite = null;
    });

    suite.compileDirective = function (template) {
      suite.element = suite.$compile(template)(suite.$scope);
      suite.directiveScope = suite.element.isolateScope();
      suite.directiveController = suite.element.controller('heavyLoad');
    };

    it('should compile correctly', function () {
      // given
      var givenTemplate = '<div heavy-load></div>';

      // when
      suite.compileDirective(givenTemplate);

      // then
      expect(suite.directiveScope.title).toBeDefined();
      expect(suite.directiveScope.items).toBeDefined();
      expect(suite.heavyLoad.getHeavyString).toHaveBeenCalled();
      expect(suite.heavyLoad.getHeavyList).toHaveBeenCalled();
    });

});
Run Code Online (Sandbox Code Playgroud)

取自这里.

这应该可以显着减少内存泄漏.您还应该查看模块结构和模块所具有的依赖关系图,因为您可能拥有某些测试不需要的模块,但无论如何都会加载它们.它们可能会占用大量内存或包含内存泄漏,并可能使您遇到其他问题.你也可以看看这个github项目.