gpt4 book ai didi

javascript - 如何从 beforeEach 函数访问有关当前运行的测试用例的信息?

转载 作者:行者123 更新时间:2023-12-01 02:27:26 25 4
gpt4 key购买 nike

使用 Protractor 5.1.2 和 Jasmine2 来描述测试用例,如何获取在 beforeEach 方法中运行的当前测试用例/规范?

我想根据我正在运行的测试用例进行一些不同的设置。我不想将这些测试放在具有重复代码的不同规范文件中,除了我想在设置中更改的一点点之外。

我正在寻找的示例:

...
beforeEach(() => {
if(currentSpec/TestCase.name == "thisName") {
// Do a particular login specific to testcase.name
} else {
// Do a default login
}
});
...

我对此的研究提出了更旧的解决方案(2年以上),这些解决方案非常过时,并且似乎一直在说访问当前运行的测试用例/规范是他们( Protractor )试图隐藏的东西。我觉得想要在一组测试用例中为特定测试用例进行特定设置并不是一件独特的事情。我可能只是使用了错误的搜索词。

最佳答案

我不确定如何使用 beforeEach() 执行您想要的操作。但是,我认为使用辅助文件可以获得相同的效果。这将允许您设置一个任何规范都可以引用的通用文件,以便您可以使用一组通用的函数。要进行此设置,您将:

创建一个中心文件(我称之为 util.js)

const helper = function(){
this.exampleFunction = function(num){
return num; //insert function here
}
this.exampleFunction2 = function(elem){
elem.click() //insert function here
}
}

在您的 spec.js 文件中,您将执行以下操作:

const help = require('path/to/util.js');
const util = new help();
describe('Example with util',function(){
it('Should use util to click an element',function(){
let elem = $('div.yourItem');
util.exampleFunction2(elem);
});
});

然后您可以从任何规范文件调用这些函数。然后,您将能够将测试分成单独的规范文件,但对于相同的部分有一组通用的函数。

无需创建单独文件即可实现此目的的另一种方法是仅使用本地函数。
示例 spec.js 文件:

describe('Should use functions',function(){
afterEach(function(){
$('button.logout').click();
)};
it('Should run test as user 1',function(){
$('#Username').sendKeys('User1');
$('#Password').sendKeys('Password1');
$('button.login).click();
doStuff();
)};
it('Should run test as user 2',function(){
$('#Username').sendKeys('User2');
$('#Password').sendKeys('Password2');
$('button.login').click();
doStuff();
)};
function doStuff(){
$('div.thing1').click();
$('div.thing2').click();
)};
)};

根据多个描述的评论:

describe('Test with user 1',function(){   
beforeEach(function(){
//login as user 1
});
it('Should do a thing',function(){
//does the thing as user 1
});
});
describe('Test with user 2',function(){
beforeEach(function(){
//login as user 2
});
it('Should do another thing',function(){
//does the other thing as user 2
});
});

关于javascript - 如何从 beforeEach 函数访问有关当前运行的测试用例的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48628578/

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