我正在尝试在 Node.js 上使用 Selenium Webdriver 和 Cucumber.js 设置测试。
我检查了 homePageSteps.js 文件,以简单地查看页面上是否存在横幅,例如:
Then('there should be a banner', async function() {
var banner = await this.driver.findElement(By.className('banner')).getRect();
assert.ok(banner.height!==null);
});
这可行,但我认为最好看看是否可以提取此检查以在任何步骤文件上使用。所以,我创建了一个新文件 banners.js:
function checkBanner(driver) {
var banner = this.driver.findElement(By.className('banner')).getRect();
return banner.height;
};
module.exports = { checkBanner };
在我的黄瓜步骤文件中:
const banners = require("../../support/components/banners");
// Other things...
Then('there should be a banner', async function() {
assert.ok(banners.checkBanner()!==null);
});
但是这当然会失败,因为
banners.js
文件不知道我们正在访问哪个页面Cannot read properties of undefined (reading 'findElement')
。
有谁知道是否有办法用 Selenium 做到这一点?
const { By } = require('selenium-webdriver');
async function checkBanner(driver) {
const banner = await driver.findElement(By.className('banner')).getRect();
return banner.height;
}
module.exports = { checkBanner };
将
this.driver
传递到步骤文件中的 checkBanner 方法:
const banners = require("../../support/components/banners");
// Other things...
Then('there should be a banner', async function() {
const bannerHeight = await banners.checkBanner(this.driver);
assert.ok(bannerHeight !== null);
});
您可以通过向 checkBanner 提供
this.driver
来确保驱动程序实例在函数中可用。这允许您在多个步骤文件中重复使用 checkBanner 函数。