如何使用Protractor等待元素的属性改变为特定值
简介 :Protractor是为AngularJS应用开发的端到端测试框架,但它也适用于非Angular JS应用。它以真实用户的方式与应用程序进行交互,并在真实浏览器中运行测试。在本文中,我们将使用Protractor来检查如何等待元素的属性改变为特定值。
前提条件 :安装和设置Protractor
步骤: 我们将创建一个基本的测试程序,其中我们将检查如何等待元素的属性改变为特定值。所有Protractor测试都将有一个包含配置的文件,这将是启动测试的初始文件。
以下是上述方法的逐步实现:
步骤1: 我们首先必须创建一个conf.js文件,其中包含要与Protractor一起使用的配置。
Javascript
exports.config = {
// Define the capabilities to be passed
// to the webdriver instance
capabilities: {
browserName: "chrome",
},
// Define the framework to be use
framework: "jasmine",
// Define the Spec patterns. This is relative
// to the current working directory when
// protractor is called
specs: ["test.js"],
SELENIUM_PROMISE_MANAGER: false,
// Define the options to be used with Jasmine
jasmineNodeOpts: {
defaultTimeoutInterval: 30000,
},
// Define the baseUrl for the file
baseUrl: "file://" + __dirname + "/",
onPrepare: function () {
browser.resetUrl = "file://";
},
};
步骤2: 我们将创建名为test.html的HTML文件,该文件将创建一个新的选项卡。
Javascript
<!DOCTYPE html>
<html>
<body>
<input type="text" id="text" name="name"
placeholder="Enter your Name" required>
<script>
setTimeout(() => {
document.getElementsByName('name')[0]
.placeholder = 'Test text change';
}, 5000)
</script>
</body>
</html>
步骤3:
我们将创建test.js文件。在这个文件中,我们将会访问上述的HTML文件,并等待元素的属性变为特定的值。浏览器是由Protractor创建的全局对象,它用于浏览器级别的命令,例如使用browser.get()方法进行导航。describe和it的语法来自Jasmine框架,其中describe是您的测试的描述,而it定义了测试的步骤。
Javascript
describe('Protractor Demo App', function () {
it("should wait for attribute's value to change to a particular value",
async function () {
var EC = protractor.ExpectedConditions;
// Disable waiting for Angular render update
await browser.waitForAngularEnabled(false)
// Get the HTML file that has to be tested
await browser.get('test.html');
// Get the test Element
var testElement = element(by.id('text'));
// Waits for the attribute's value to change
// to a particular value
await browser.wait(async function() {
return await testElement.getAttribute('placeholder') ===
'Test text change';}, 10000, 'Takes time to load');
});
});
步骤4: 最后,我们将使用以下命令来运行配置文件。这将运行配置文件,并且测试结果将如下所示。
protractor conf.js
输出: