1

我编写了一个辅助方法来在 Puppeteer 页面实例上添加一个网络响应侦听器。代码看起来像这样

let Helper = codecept_helper;

class CheckHelper extends Helper {
  async listenRequest(listener)
  {
    const helper = this.helpers['Puppeteer'];
    await helper.page.setRequestInterception(true);
    helper.page.on("request",listener);
    return helper._waitForAction();
  }
  async listenResponse(listener)
  {
    const helper = this.helpers['Puppeteer'];
    helper.page.on("response",listener);
    return helper._waitForAction();
  }
}

module.exports = CheckHelper;

然后在测试脚本中

  let self=this;
  I.listenResponse((response)=>{
     if(response.url().match(/github.*\.js/) && response.headers()['content-length']>1000) {
         //codeceptjs.event.emit(codeceptjs.event.test.failed, self, 'js file is too big!');
         //codeceptjs.recorder.throw('js file is too big!')
         //codeceptjs.recorder.stop();
         //throw new Error('js file is too big!')
     }
  })
  I.amOnPage("https://www.github.com");

我首先添加响应侦听器,然后我转到“github”,当某些 js 文件大小太大时,我会抛出一个错误,以便检查内容大小是否正确。

但是,即使我抛出错误(就像注释代码那样),主要的测试流程也不会停止,我该怎么做才是正确的方法?

4

1 回答 1

1

好吧,我后来找到了解决方案

我将所有页面响应记录到页面实例中的自定义对象中。后来我写了一个帮助方法来检查整个记录。

//in helper.js
startRecordResponse() {
    const helper = this.helpers['Puppeteer'];
    helper.page.on("response", (res) => {
        //record all response instance into savedResponse object inside page, we'll use it later
        helper.page.savedResponse = helper.page.savedResponse || {};
        helper.page.savedResponse[res.url()] = res;
    });
    return helper._waitForAction();
}

checkFileIsTooBig(filter, sizeLimit) {
    const helper = this.helpers['Puppeteer'];
    //use the data recorded in savedResponse object 
    Object.keys(helper.page.savedResponse).forEach((url) => {
        var res = helper.page.savedResponse[url];
        if (((filter instanceof RegExp && filter.test(url)) || (typeof filter == "string" && url.indexOf(filter) != -1)) && res.headers()['content-length'] > sizeLimit) {
            throw new Error(`file ${url} is too big,${res.headers()['content-length']} > ${sizeLimit}`)
        }
    })
    return helper._waitForAction();
}

然后在测试文件中

Before((I) => {
  I.startRecordResponse();
  I.amOnPage("https://www.github.com");
});

Scenario('github_test', (I) => {
        //check a js file contain github is less than 100 bytes
        I.checkFileIsTooBig(/github.*\.js/,100);
    }
);
于 2018-11-16T08:28:52.663 回答