如何使用Cucumber-js使用Puppeteer和Headless Chrome

时间:2017-10-05 19:04:36

标签: javascript cucumber cucumberjs google-chrome-headless puppeteer

我正在尝试使用cucumber-js进行BDD并使用Headless Chrome和puppeteer推动浏览器测试。

使用cucumber node exampleheadless chrome中的文档,我收到以下错误,整个代码库可在此处使用:github repo

错误:

  1. TypeError:this.browser.newPage不是函数
  2. TypeError:this.browser.close不是函数
  3. // 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');
        });
    });
    

3 个答案:

答案 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 的工作:

  1. 运行upperBound
  2. 在项目的根目录中创建一个 npm install puppeteer-cucumber-js 文件夹
  3. 添加带有 features 语句的 feature-name.feature 文件
  4. 创建一个 Given, When, Then 文件夹
  5. 为每个功能步骤添加要执行的 JavaScript 步骤
  6. 运行测试 features/step-definitions

带有 GitHub 上的工作示例的源代码