前端自动化测试框架Cypress(二十三)生成测试报告(二)

25 篇文章 18 订阅
25 篇文章 18 订阅

一、编写动态挑选测试用例运行代码

在项目根目录文件夹下简历utils文件夹,在此文件夹下新建PickTestsToRun.js

//PickTestsToRun.js
/*本段代码更改it和describe的行为,使之实现类似mocha中的grep功能,接受如下四个参数
1、-i <value>,仅运行指定的it()。该it()的描述中含有<value>
2、-I <value>,仅运行指定的describe()。该describe()的描述中含有<value>
3、-e <value>,排除指定的it()。该describe()的描述中含有<value>
4、-E <value>,排除指定的describe()。该describe()的描述中含有<value>
*/
function pickIts() {
    if (global.it.itHadSet) return;

    const include = Cypress.env('i') && Cypress.env('i').split(',');
    const exclude = Cypress.env('e') && Cypress.env('e').split(',');
    const originIt = it;

    global.it = function (...rest) {
        const itDesc = rest[0];
        if (include) {
            if (include.findIndex(item => itDesc.indexOf(item) > -1) > -1) {
                originIt(...rest)
            }
        }
        if (exclude) {
            if (!(exclude.findIndex(item => itDesc.indexOf(item) > -1) > -1)) {
                originIt(...rest)
            }
        }
        if (!exclude && ! include){
            originIt(...rest)
        }
    };
    global.it.itHadSet = true
}

function pickDescribes() {
    if (global.describe.describeHadSet) return;

    const include = Cypress.env('I') && Cypress.env('I').split(',');
    const exclude = Cypress.env('E') && Cypress.env('E').split(',');
    const originDescribe = describe;

    global.describe = function (...rest) {
        const describeDesc = rest[0];
        if (include) {
            if (include.findIndex(item => describeDesc.indexOf(item) > -1) > -1) {
                originDescribe(...rest)
            }
        }
        if (exclude) {
            if (!(exclude.findIndex(item => describeDesc.indexOf(item) > -1) > -1)) {
                originDescribe(...rest)
            }
        }
        if (!exclude && ! include){
            originDescribe(...rest)
        }
    };
    global.describe.describeHadSet = true
}

pickIts();
pickDescribes();

二、动态挑选用例配置及动态更改运行环境配置

在cypress/support/index.js文件里,引入PickTestsToRun.js,及动态配置测试环境

//引入 PickTestsToRun
require('../utils/PickTestsToRun');

//动态指定运行环境
beforeEach(function () {
    const targetEnv = Cypress.env('testEnv') || Cypress.config('targetEnv');
    cy.log(`Set target environment to: \n ${JSON.stringify(targetEnv)}`);
    cy.log(`Environment details are: \n ${JSON.stringify(Cypress.env(targetEnv))}`);
    Cypress.config('baseUrl', Cypress.env(targetEnv).baseUrl);
    cy.log('Now the test starting...')
});

三、配置项目文件cypress.json

{
  "targetEnv": "patch",
  "baseUrl": "http://192.168.1.159:38009",
  "env": {
    "new": {
      "baseUrl": "https://newhcdweb.huochaoduo.com"
    },
    "patch": {
      "baseUrl": "http://192.168.1.159:38009"
    }
  }
}

四、编写Module API运行项目及融合测试报告代码

在项目根目录下建立moduleRunIndex.js

///<reference types="cypress" />

const cypress = require('cypress');
const fse = require('fs-extra');
const {merge} = require('mochawesome-merge');
const generator = require('mochawesome-report-generator');
var colors = require('colors');
const program = require('commander');
const moment = require('moment');

program
    .requiredOption('-t, --targetEnvironment <string>', 'Specify the running Env','patch')
    .requiredOption('-s, --specFile <string>', 'Spec the running file path', 'cypress/integration/*')
    .option('-i, --onlyRunTest <string>', 'Only run the test cases in it(), for example -i smoke, run cases that contains smoke in description')
    .option('-e, --excludeTest <string>', 'Exclude to run the test cases in it(), for example -i smoke, run cases that contains smoke in description')
    .option('-I, --onlyRunSuites <string>', 'Only run the test suites in describe(), for example -I smoke, run test suites that contains smoke in description')
    .option('-E, --excludeSuites <string>', 'Only run the test suites in describe(), for example -E smoke, exclude to run test suites that contains smoke in description')
    .allowUnknownOption()
    .parse(process.argv);

var envParams;
var args = program.opts();
envParams = `testEnv=${args.targetEnvironment}`;

if (args.onlyRunTest) envParams = envParams.concat(`,i=${args.onlyRunTest}`);
if (args.excludeTest) envParams = envParams.concat(`,e=${args.excludeTest}`);
if (args.onlyRunSuites) envParams = envParams.concat(`,I=${args.onlyRunSuites}`);
if (args.excludeSuites) envParams = envParams.concat(`,E=${args.excludeSuites}`);

function getTimeStamp() {
    let now = new moment().format('YYYY-MM-DD--HH__MM__SS')
    return now
}

const currRunTimestamp = getTimeStamp();

const sourceReport = {
    reportDir: `${'report/' + 'Test Run - '}${currRunTimestamp}/mochawesome-report`,
    saveJson: true,
    reportFilename: 'Run-Report',
    reportTitle: 'Run-Report',
    reportPageTitle: 'Run-Report',
};

async function mergeReport() {
    console.log(`The target Enviroment are set to: ${program.targetEnvironment}`.bold.yellow);
    console.log(`The target TestPath are et to: ${program.specFile}`.bold.yellow);
    console.log(`The running Env are : ${envParams}`.bold.yellow);

    fse.ensureDirSync(sourceReport.reportDir);

    const {totalFailed} = await cypress.run({
        spec: `${args.specFile}`,
        //Cypress run with provided parameters.
        env: envParams,
        browser: 'chrome',
        config: {
            pageLoadTimeout: 30000,
            screenshotsFolder: `${sourceReport.reportDir}/screenshots`,
            video: false,
            videosFolder: `${sourceReport.reportDir}/videos`,
        },
        reporter: 'mochawesome',
        reporterOptions: {
            reportDir: sourceReport.reportDir,
            overwrite: false,
            html: true,
            json: true,
        },
    });
    const jsonReport = await merge(sourceReport);
    await generator.create(jsonReport, finalReport);
    process.exit(totalFailed);
}
mergeReport();

五、配置package.json文件

"scripts": {
  "ModuleRun": "node moduleRunIndex.js",
  "cypress:open": "cypress open"
},

六、安装测试报告融合依赖

//安装Mochawesome

npm install modulewesome -D

//以下安装切换至项目根目录下进行

npm install mocha@5.2.0 --save-dev

//安装mochawesome-merge

npm install mochawesome-merge --save-dev

//安装commander

npm install commander --save-dev

//安装mochawesome-report-generator

npm install mochawesome-report-generator --save-dev

七、指定参数运行并看结果

Yarn ModuleRun -t patch -i login
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值