Я новичок в транспортире и javascript. Я создаю тестовую среду, в которой каждый тестовый костюм имеет соответствующий файл модуля и файл локатора. В тестовых примерах файла тестового костюма тестовые модули вызываются с помощью передаваемого параметра. Когда я попытался вложить вызываемую функцию из модуля в блок «затем»; затем блоки начинают выполнение до завершения вызванной функции. Обратитесь к следующим файлам кода:
UserPage.js // Test suit from where modules are called
var d = require("../Data/TestCaseData.js");
var login = require("../Modules/LoginPageModule.js");
var user = require("../Modules/UserPageModule.js");
var userl = require("../Locators/UserPageLocators");
describe('first test suit',function(){
beforeEach(function(){
browser.get(d.iManUrl).then(function(){
browser.manage().window().maximize();
login.OSPLogin(d.username,d.password);
})
});
it ('Creating user',function(){
var person = {'Username' : 'u6' , 'Context' : 'novell' , 'Last name' : 'last' , 'Password' : 'n'};
user.InputData(person).then(function(){
element(by.buttonText("Create")).click().then(function(){
browser.sleep(5000);
});
})
})
})
Ниже модуль:
var usercreated = false;
function UserPageModule(){
this.InputData = function(person){
return this.InputUserPasswordContext(person).then(function(person){
this.fill =function(data){
for (var key in data) {
console.info(key);
element(by.xpath(user.identificationAddValueButtonXpath.replace("Input Field", key))).click();
element(by.css(user.identificationValueInputCss)).sendKeys(person [ key ]);
element(by.buttonText(user.identificationAcceptValueButtonText)).click();
}
}
return new Promise(function(resolve,request){
return resolve(this.fill(person));
})
});
}
/*this.InputData = function(person){
this.InputUserPasswordContext(person).then(function(person){
this.InputFields(person);
});
}*/
this.InputUserPasswordContext = function(person){
return new Promise(function(resolve,reject){
//Navigating to user page
element(by.css(landing.userLinkCss)).click();
//Clicking on add button
element(by.css(user.createuserButtonCss)).click();
//Inputting Username
element(by.css(user.usernameInputCss)).sendKeys(person.Username).then(function(){
delete person.Username;
});
//Input password
element(by.css(user.identificationPasswordInputCss)).sendKeys(person.Password);
element(by.css(user.identificationRetypeInputCss)).sendKeys(person.Password).then(function(){
delete person.Password;
});
//Inputting context
element(by.css(user.contextInputCss)).sendKeys(person.Context).then(function(){
delete person.Context;
}).then(function(){
resolve(person);
})
})
}
}
module.exports = new UserPageModule
Все шаги выполняются последовательно до цикла for. Но затем блоки выполняются перед циклом for. Я также не получаю никаких ошибок.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Для Javascript каждый Function имеет неявный this. Когда вы используете вложенную функцию, легко ошибиться при использовании this.
function UserPageModule(){
this.InputData = function(person){
return this.InputUserPasswordContext(person).then(function abc(person){
for (let key in data) {
console.info(key);
element(by.xpath(user.identificationAddValueButtonXpath.replace("Input Field", key))).click();
element(by.css(user.identificationValueInputCss)).sendKeys(person [ key ]);
element(by.buttonText(user.identificationAcceptValueButtonText)).click();
}
}).catch(function(err){
console.info('err: ' + err);
});
}
this.InputUserPasswordContext = function(person){
...
}
}
Дополнительная информация: в разделе beforeEach 'login.OSPLogin(d.username,d.password);' не возвращает обещание. Но я думаю, это не должно быть проблемой.
Попробуйте изменить for (var key in data) { на for (let key in data) {
Я попытался изменить, но такое же поведение. Даже если я возвращаю простой оператор или переменную вместо метода «xyz»; Блок «тогда» выполняется первым.
Я удаляю return new Promise() и добавляю catch на случай возникновения ошибки в InputUserPasswordContext(). Пожалуйста, попробуйте еще раз.
Это решение не сработало. Наблюдения: 1 - Все, что возвращается с помощью "return resolve();" функции 'xyz' выполняется после блока "user.InputData(person).then(function(value){ element(by.buttonText("Create")).click(); }) ", который является разделом теста рассматриваемый блок дела