一、mochawesome提供了addContext方法来给测试报告添加内容
addContext有两个参数,第一个参数传递mocha的this实例,第二个参数可以自定义传递。
首先对格式化的内容进行封装
/**
* mochawesome格式化输出
* @param obj 传入请求的response对象
* @returns {{title: string, value: {}}|{title: string, value: {requestHeaders: any, responseHeaders, responseBody, requestBody: any, requestUrl: string}}}
*/
exports.add = function (obj) {
let options ;
if (obj !== null) {
options = {
title: 'response',
value: {
requestUrl: obj.config.method + ": " + obj.config.baseURL + obj.config.url,
requestHeaders: obj.config.headers,
requestBody: obj.config.data,
responseHeaders: obj.headers,
responseBody: obj.data,
}
}
} else
options = {title: 'response',value: {}};
return options
}
二、在用例中引入
在beforeEach中进行初始化
在afterEach中调用addContext
/**
* 首页接口用例
* @type {AxiosStatic | {CancelTokenSource: CancelTokenSource, CancelStatic: CancelStatic, AxiosProxyConfig: AxiosProxyConfig, Canceler: Canceler, AxiosStatic: AxiosStatic, AxiosRequestConfig: AxiosRequestConfig, AxiosTransformer: AxiosTransformer, Cancel: Cancel, AxiosInstance: AxiosInstance, AxiosError: AxiosError, Method: Method, AxiosPromise: AxiosPromise, CancelTokenStatic: CancelTokenStatic, AxiosBasicCredentials: AxiosBasicCredentials, ResponseType: ResponseType, CancelToken: CancelToken, AxiosInterceptorManager: AxiosInterceptorManager, AxiosResponse: AxiosResponse, AxiosAdapter: AxiosAdapter, readonly default: AxiosStatic}}
*/
const axios = require('axios')
const defaults = require('../../config/global/defaults');
const path = require('../../config/global/path');
const addContext = require('mochawesome/addContext');
const utilFormat = require('../../utils/format');
const homePageCase = require('../../config/case/homepagecase');
const compare = require('../../utils/compare');
describe('home', function () {
let obj;
beforeEach(function () {
obj = null;
})
afterEach(function () {
addContext(this, utilFormat.add(obj));
});
context('homeList', function () {
it('current', async function () {
let name = this._runnable.title;
await axios.get(path.homePagePathList.current, {
headers: {'Cookie': defaults.session}
})
.then(function (res) {
obj = res;
for (let i of homePageCase.homePage) {
if (i['requestName'] === name) {
compare.compare(i['res'], res.data);
}
}
})
.catch(function (error) {
should.ifError(error);
})
});
})
})
三、展示效果
每个请求的request和response都在报告上展示了