[英]Protractor set global variables
我正在嘗試在量角器上設置一個全局變量以在所有描述塊中使用。
var glob = 'test';
describe('glob test', function () {
it('should set glob', function () {
browser.get('http://example.com/test');
browser.executeScript(function () {
window.glob = glob;
});
});
});
但這會返回以下錯誤:
Message:
[firefox #2] UnknownError: glob is not defined
我也看了這個問題: protractor angularJS global variables
所以我嘗試以這種方式在 conf.js 中設置變量 glob:
exports.config = {
...,
onPrepare: function () {
global.glob = 'test';
}
};
仍然,有同樣的錯誤。
如何在量角器測試中正確添加全局變量?
可以在params
屬性的幫助下從 Protractor 配置文件設置全局變量:
exports.config = {
// ...
params: {
glob: 'test'
}
// ...
};
您可以使用browser.params.glob
在規范中訪問它。
請參閱參考配置文件。
params 對象將直接傳遞給 Protractor 實例,並且可以作為 browser.params 從您的測試中訪問。 它是一個任意對象,可以包含您在測試中可能需要的任何內容。 這可以通過命令行更改為:
protractor conf.js --params.glob 'other test'
更新:
如果腳本作為函數對象提供,則該函數將轉換為字符串以注入目標窗口。 除了腳本之外提供的任何參數都將作為腳本參數包含在內,並且可以使用參數對象進行引用。
因此,在這種情況下,JavaScript 范圍不起作用,傳遞給browser.executeScript
函數不會像browser
那樣具有任何來自規范的閉包變量。 但是您可以顯式傳遞這些變量:
browser.executeScript(function (glob) {
// use passed variables on the page
console.log(glob);
}, browser.params.glob);
您還可以使用global
在onPrepare()
設置全局變量:
onPrepare: function () {
global.myVariable = "test";
},
然后,您只需在整個測試中按myVariable
使用myVariable
。
這實際上是protractor
、 browser
和其他內置全局變量如何全局可用:
Runner.prototype.setupGlobals_ = function(browser_) {
// Export protractor to the global namespace to be used in tests.
global.protractor = protractor;
global.browser = browser_;
global.$ = browser_.$;
global.$$ = browser_.$$;
global.element = browser_.element;
global.by = global.By = protractor.By;
// ...
}
請注意,使用這種方法會污染全局范圍/命名空間,請小心。
另一種選擇是使用過程變量
量角器是一個節點進程。 任何節點進程都可以使用自定義節點變量啟動。 不確定它是如何在 Windows 中完成的(如果你知道如何,請發表評論)但對於 mac 和任何 linux/unix 操作系統,你可以
用這樣的環境變量啟動量角器
MY_VAR=Dev protractor tmp/config.js
然后它將在您的流程中的任何地方甚至在您的配置中可用
console.log(process.env.MY_VAR)
我知道我的答案有點晚了,但這是設置可在整個文件中使用的全局變量的另一種方法
describe("Some Global most outer describe", function(){
var glob = "some global variable";
var blob = "some other global variable";
it('should test glob', function(){
expecte(glob).toEqual("some global variable");
});
it('should test blob', function(){
expecte(glob).toEqual("some other global variable");
});
describe('Some inner describe', function(){
//Some other inner tests can also see glob and blob
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.