node.js - 通过 Newman 运行 Postman 脚本时出错
问题描述
我正在尝试通过 Newman 运行以下 Postman 脚本以将响应写入文件:
//verify http response code
pm.test("Report Generated", function () {
pm.response.to.have.status(200);
});
var fs = require('fs');
var outputFilename = 'C:/Users/archit.goyal/Downloads/spaceReport.csv';
fs.writeFileSync(outputFilename, pm.response.text());
请求给出响应,但在写入文件时出现以下错误:1?测试脚本中的 TypeError
┌─────────────────────────┬──────────┬──────────┐
│ │ executed │ failed │
├─────────────────────────┼──────────┼──────────┤
│ iterations │ 1 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ requests │ 20 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ test-scripts │ 20 │ 1 │
├─────────────────────────┼──────────┼──────────┤
│ prerequest-scripts │ 0 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ assertions │ 2 │ 0 │
├─────────────────────────┴──────────┴──────────┤
│ total run duration: 1m 48.3s │
├───────────────────────────────────────────────┤
│ total data received: 1.24MB (approx) │
├───────────────────────────────────────────────┤
│ average response time: 5.3s │
└───────────────────────────────────────────────┘
# failure detail
1. TypeError fs.writeFileSync is not a function
at test-script
inside "3i_BMS_Amortization_Schedule / GetReport"
请帮忙
解决方案
Postman 本身不能执行这样的脚本。要保存所有 api 请求的响应,您可以创建一个 nodeJS 服务器,它将通过 newman 调用 api,然后将响应保存到本地文件。这是一个例子 -
var fs = require('fs'),
newman = require('newman'),
allResponse=[],
outputFilename = 'C:/Users/archit.goyal/Downloads/spaceReport.csv';
newman.run({
collection: '//your_collection_name.json',
iterationCount : 1
})
.on('request', function (err, args) {
if (!err) {
//console.log(args); // --> args contain ALL the data newman provides to this script.
var responseBody = args.response.stream,
response = responseBody.toString();
allResponse.push(JSON.parse(response));
}
})
.on('done', function (err, summary) {
fs.writeFile(outputFilename,"");
for(var i =0;i<allResponse.length;i++)
{
fs.appendFileSync(outputFilename,JSON.stringify(allResponse[i],null,5));
}
});
请注意,上面的代码将只保存响应。其他数据如 request 或 URl 可以以类似的方式提取。要运行它,请安装newman
在与脚本相同的目录中,然后使用 -
node file_name.js
推荐阅读
- spring-boot - 如何使用 undertow 在 Spring Boot 中禁用管理上下文访问日志
- google-apps-script - 谷歌应用脚本导出 csv 用分号而不是逗号
- arrays - Swift,将数组分配给变量的问题
- sql - 仅从数据库中获取用户尚未看到的 100 行
- java - 如何在java中抑制空指针访问警告?
- python - 无法将对象检测模型转换为 tflite
- bash - 有没有办法根据脚本本身的值设置 slurm 脚本作业数组的大小?
- iis - 关闭 VS2019 后应用程序池停止
- vbscript - 路径有效时删除方法vbscript生成路径未找到错误
- perl - 如何使用 foreach 访问数组的元素?