如何为Jasmine/Angular创建一个帮助器来组合多个beforeEach

jha*_*amm 20 javascript jasmine angularjs karma-runner

我一直在我的spec文件中重复一些注入模板然后编译它的代码.我将这段代码提取到一个辅助函数中,以保持干燥.我认为问题在于试图将其置于beforeEach辅助函数中.这是我试图抽象成函数的代码片段:

  beforeEach(module('app/views/header.html'));

  beforeEach(inject(function($templateCache, $compile, $rootScope) {
    template = $templateCache.get('app/views/header.html');
    $templateCache.put('views/header.html', template);
    var directive = angular.element('<clinical-header></clinical-header>');
    element = $compile(directive)($rootScope);
    $rootScope.$digest();
  }));
Run Code Online (Sandbox Code Playgroud)

这是我创建的辅助函数:

var setupTemplate = function(templateName, element) {
  beforeEach(module('app/views/' + templateName));
  beforeEach(inject(function($templateCache, $compile, $rootScope) {
    var template = $templateCache.get('app/views/' + templateName);
    $templateCache.put('views/' + templateName, template);
    var directive = angular.element(element);
    element = $compile(directive)($rootScope);
    $rootScope.$digest();
  }));
Run Code Online (Sandbox Code Playgroud)

现在这是对辅助函数的调用:

setupTemplate('header.html', '<clinical-header></clinical-header>');
Run Code Online (Sandbox Code Playgroud)

在我的辅助函数结束时,一切看起来都不错,但是当我跳到我的it块时,一切都是未定义的.我可以提取多个beforeEach?这样做的正确方法是什么?另外,放置茉莉花辅助功能的适当位置在哪里?如何完成?

Eit*_*eer 16

您可以通过将它们写在特定describe函数的上下文之外来创建全局beforeEach()函数.您应该使用这些函数创建一个spec-helper.js类,并通过Karma config加载它.

请注意,beforeEach函数将在您运行的任何函数之前执行(因为它们是全局函数).

我创建了一个小提琴来演示,但是Karma的关键是将文件添加到配置中,以便浏览器加载它.

规范助手:

var myGlobal;
beforeEach(function() {
    // This will run before any it function.
    // Resetting a global state so the change in this function is testable
   myGlobal = 10
});
Run Code Online (Sandbox Code Playgroud)

测试套件:

describe('first suite', function(){
   it('is a test', function(){
     expect(myGlobal).toBe(10);
     // Reset the value to show that beforeEach is executed for each it function
     myGlobal = 20;
     expect(myGlobal).toBe(20);
  });

  it('is another test', function($location){
     expect(myGlobal).toBe(10);
     myGlobal = 20;
     expect(myGlobal).toBe(20);
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 我的项目情况非常相似.我在函数内部包含了我的全局`beforeEach`调用,只需在我的`describe`块的顶部调用该函数,用于任何需要它的测试套件. (3认同)
  • 如果您只想运行测试子集的代码,并且测试位于单独的文件中,则无法解决问题. (2认同)