問題描述
Protractor 測試框架的可重用函數 (Reusable functions for Protractor test framework)
我使用 Protractor 測試框架,需要針對不同的情況使用一些相同的操作。像身份驗證過程。
問題是:在量角器中使用自己的函數的正確方法是什麼?
我記得這個工具有效:1)異步和2) 它的函數返回promise。
可重用函數必須返回promise 以使可能做.then() 操作,否則這個函數可能沒有返回值?
一個例子(正確或否):
describe('Login procedure', function() {
it('Login Username', function () {
browser.get('anurl.com');
auth('username', 'password').then(function(){console.log('NICE TO MEET YOU')});
});
var auth = function(loginstr, passwordstr) {
return element(by.css('div[class="login"]')).isDisplayed().then(function (result) {
if (result) {
element(by.css('input[name="email"]')).clear().sendKeys(loginstr).then(
function () {
element(by.css('input[name="password"]')).clear().sendKeys(passwordstr).then(function () {
element(by.css('button[class="submit"]')).click().then(function () {
return element(by.id('welcome')).isPresent();
});
});
});
}
});
}
謝謝!
參考解法
方法 1:
Your example looks fine.
It is good practice to return a promise from your utility functions (so callers can then
off of it if they want). But it is not required.
In practice, the methods you are invoking that create promises (e.g., click
or isDisplayed
, etc) implicitly register the created promise with the control flow, so the implicit synchronization will not be impacted by refactoring the calls into your own functions.
See the Protractor Page Objects for a similar approach.
方法 2:
Our team uses Orchid‑js with Jasmine and Protractor.
It's an extension that makes defining your own functions automatic.
In this case your code will still work, you would just be able to automatically reuse your 'Login procedure' and 'Login Username' functions as well.
Describe('Login procedure', function(username,password) {
It('Login Username', function (username,password) {
browser.get('anurl.com');
auth(username, password).then(function(){console.log('NICE TO MEET YOU')});
})(username,password);
})('username','password');
Then reuse it later
Describe('Login procedure')('differentUsername','differentPassword');
(by Volodymyr Nabok、P.T.、Marshall Bean)