我正在尝试使用cucumber-js进行BDD并使用Headless Chrome和puppeteer推动浏览器测试。
使用cucumber node example和headless chrome中的文档,我收到以下错误,整个代码库可在此处使用:github repo。
错误:
// features / support / world.js
const puppeteer = require('puppeteer');
var {defineSupportCode} = require('cucumber');
function CustomWorld() {
this.browser = puppeteer.launch();
}
defineSupportCode(function({setWorldConstructor}) {
setWorldConstructor(CustomWorld)
})
// features / step_definitions / hooks.js
const puppeteer = require('puppeteer');
var {defineSupportCode} = require('cucumber');
defineSupportCode(function({After}) {
After(function() {
return this.browser.close();
});
});
// features / step_definitions / browser_steps.js
const puppeteer = require('puppeteer');
var { defineSupportCode } = require('cucumber');
defineSupportCode(function ({ Given, When, Then }) {
Given('I am on the Cucumber.js GitHub repository', function (callback) {
const page = this.browser.newPage();
return page.goto('https://github.com/cucumber/cucumber-js/tree/master');
});
When('I click on {string}', function (string, callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
Then('I should see {string}', function (string, callback) {
// Write code here that turns the phrase above into concrete actions
callback(null, 'pending');
});
});
答案 0 :(得分:2)
puppeteer是完全异步的,因此在使用this.browser
之前你必须等待它的初始化。
但是setWorldConstructor是同步功能,所以你不能在那里等。在我的例子中,我使用了Before hook
我的例子: https://gist.github.com/dmitrika/7dee618842c00fbc35418b901735656b
答案 1 :(得分:1)
黄瓜已经更新。这就是我用黄瓜实现我的async puppeteer设置的方法。要点here
const { BeforeAll, Before, AfterAll, After } = require('cucumber');
const puppeteer = require('puppeteer');
Before(async function() {
const browser = await puppeteer.launch({ headless: false, slowMo: 50 });
const page = await browser.newPage();
this.browser = browser;
this.page = page;
})
After(async function() {
// Teardown browser
if (this.browser) {
await this.browser.close();
}
// Cleanup DB
})
答案 2 :(得分:1)
我们创建了 puppeteer-cucumber-js 来简化 Puppeteer 和 Cucumber 的工作:
upperBound
npm install puppeteer-cucumber-js
文件夹features
语句的 feature-name.feature
文件Given, When, Then
文件夹features/step-definitions
带有 GitHub 上的工作示例的源代码