gpt4 book ai didi

javascript - 如何为 Jasmine/Angular 创建一个助手来组合多个 beforeEach

转载 作者:行者123 更新时间:2023-12-03 08:00:52 24 4
gpt4 key购买 nike

我不断在我的规范文件中重复一些代码,这些代码注入(inject)一个模板然后编译它。我将这段代码提取到一个辅助函数中以保持干燥。我相信问题在于试图放置到 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 时 block ,一切都是未定义的。我可以提取多个 beforeEach的?这样做的正确方法是什么?此外,在哪里放置 jasmine 辅助函数的正确位置以及如何完成?

最佳答案

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

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

我创建了一个 fiddle为了演示,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);
});
});

关于javascript - 如何为 Jasmine/Angular 创建一个助手来组合多个 beforeEach,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19563130/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com