我可以在回调中动态创建测试规范吗? [英] Can I dynamically create a test spec within a callback?
问题描述
我想检索页面上的元素列表,并为每个元素创建一个测试规范。我的(伪)代码是: -
I want to retrieve a list of elements on a page, and for each one, create a test spec. My (pseudo) code is :-
fetchElements().then(element_list) {
foreach element {
it("should have some property", function() {
expect("foo")
})
}
}
当我运行它时,我得到No specs found,我认为这是有意义的,因为它们是在主路径上定义的。
When I run this, I get "No specs found", which I guess makes sense since they are being defined off the main path.
实现动态创建规格的最佳方法是什么?
What's the best way to achieve dynamically created specs?
推荐答案
存在一些主要问题阻止它轻松实现:
There are major problems preventing it to be easily achieved:
- 您创建的规范基于异步代码的结果 - 关于元素
量角器
应该首先找到 - 你只能拥有
Protractor / WebDriverJS
具体代码在it
,beforeEach
,beforeAll
,afterEach
,afterAll
以使其正常工作并将保证放在控制流等上。 - 你不能嵌套
它
blocks -jasmine
不会执行它们: 无法在另一个'it'内执行'it'
- the specs you are creating are based on the result of asynchronous code - on the elements
Protractor
should first find - you can only have the
Protractor/WebDriverJS
specific code inside theit
,beforeEach
,beforeAll
,afterEach
,afterAll
for it to work properly and have the promises put on the Control Flow etc. - you cannot have nested
it
blocks -jasmine
would not execute them: Cannot perform a 'it' inside another 'it'
如果它不是你想要生成测试用例的元素,而是一个静态变量机智ha定义的值,它将如此简单:
If it were not the elements you want to generate test cases from, but a static variable with a defined value, it would be as simple as:
describe("Check something", function () {
var arr = [
{name: "Status Reason", inclusion: true},
{name: "Status Reason", inclusion: false}
];
arr.map(function(item) {
it("should look good with item " + item, function () {
// test smth
});
});
});
但是,如果 arr
将是一个承诺,测试将在一开始就失败,因为中的代码描述
(不在
内)将被执行由jasmine加载测试。
But, if arr
would be a promise, the test would fail at the very beginning since the code inside describe
(which is not inside it
) would be executed when the tests would be loaded by jasmine.
总而言之,只有一个 it()
阻止并在其中工作:
To conclude, have a single it()
block and work inside it:
it("should have elements with a desired property", function() {
fetchElements().then(element_list) {
foreach element {
expect("foo")
})
}
}
如果您担心将测试失败与元素区分开来,您可以,例如,提供可读的错误消息,以便在测试失败时,您可以轻松地说,哪些元素未通过测试(在您的伪测试用例中没有特定属性)。例如,您可以将自定义消息提供给 expect()
:
If you are worried about distinguishing test failures from an element to element, you can, for instance, provide readable error messages so that, if a test fails, you can easily say, which of the elements has not passed the test (did not have a specific property in your pseudo-test case). For example, you can provide custom messages to expect()
:
expect(1).toEqual(2, 'because of stuff')
这篇关于我可以在回调中动态创建测试规范吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!