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

How do I create a helper for Jasmine/Angular to combine multiple beforeEach's

本文关键字:一个 帮助程序 组合 beforeEach Jasmine Angular 创建      更新时间:2023-09-26

我一直在我的规范文件中重复一些代码,这些代码注入了一个模板,然后编译它。 我将此代码提取到一个辅助函数中以保持干燥。 我相信问题在于试图在辅助函数中放置 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();
  }));

这是我创建的帮助程序函数:

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

现在这是对帮助程序函数的调用:

setupTemplate('header.html', '<clinical-header></clinical-header>');

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

您可以通过在特定描述函数的上下文之外编写全局 beforeEach() 函数来创建它们。你应该创建一个具有这些函数的规范助手.js类,并通过 Karma 配置加载它。

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

我创建了一个小提琴来演示,但是 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
});

测试套件:

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