如何将自定义定位器全局添加到量角器? [英] How to globally add a custom locator to Protractor?
问题描述
我为 Protractor 编写了一个自定义定位器,它通过 ui-sref
值查找 anchor
元素.在我的规范中,我只是使用 by.addLocator
添加自定义定位器,但我认为发布并让其他人使用它可能是一件很酷的事情.
I wrote a custom locator for Protractor that finds anchor
elements by their ui-sref
value. In my specs I just used by.addLocator
to add the custom locator, but I figured this might be a cool thing to publish and have other people use it.
我们的目标是将此自定义定位器添加到全局 Protractor 对象中,以便在您的任何规范中使用它.
The goal is to add this custom locator to the global Protractor object so it can be used in any of your specs.
我最初的方法是在 Protractor 配置的 onPrepare
块中添加此功能.类似于下面的伪代码:
My initial approach was to add this functionality in the onPrepare
block of the Protractor config. Something like the pseudocode below:
onPrepare: function () {
require('ui-sref-locator')(protractor); // The protractor object is available here.
}
那个require语句只会执行这个函数:
That require statement would just execute this function:
function (ptorInstance) {
ptorInstance.by.addLocator('uiSref', function (toState, opt_parentElement) {
var using = opt_parentElement || document;
var possibleAnchors = using.querySelectorAll('a[ui-sref="' + toState +'"]');
var result = undefined;
if (possibleAnchors.length === 0) {
result = null;
} else if (possibleAnchors.length === 1) {
result = possibleAnchors[0];
} else {
result = possibleAnchors;
}
return result;
});
};
问题是 by
没有在 onPrepare
块中可用的 protractor
对象上定义.这意味着我不能使用 .addLocator
方法.
The problem is that by
is not defined on the protractor
object available in the onPrepare
block. This means that I cannot use the .addLocator
method.
推荐答案
试试以下:
function () {
by.addLocator('uiSref', function (toState, opt_parentElement) {
...
By 应该在全局范围内.
By should be in the global scope.
这篇关于如何将自定义定位器全局添加到量角器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!