A使用page model和this配方在主测试控制器外部进行此测试。
scaffold=(
foo
bar
foobar
qux
)
n=0
while read count; do
for i in $(seq "$count"); do echo "${scaffold[n]}"; done
((n++))
done < temp
错误
针对本地http服务器运行此测试时,工作正常。但是,当测试针对https远程服务器时,它将失败。我收到此错误:
/**
Used to get the periodic analytic id.
Whenever we are viewing an asset, server must respond with an id.
This id is later used by the client, to send periodic analytics.
@param {object} t Testcafe's test controller
@param {object} logger A testcafe's RequestLogger.
@returns {string} Returns the periodic analytic id.
*/
async getPeriodicAnalyticId(t, logger) {
const logPrefix = 'Get periodic analytic id > ';
let responseBody;
await t
.expect(logger.requests.length).gt(0, logPrefix + 'No requests logged.');
responseBody = logger.requests[0].response.body;
await t
.expect(responseBody).notTypeOf('undefined', logPrefix + 'Logged request does not have a response a body.')
.expect(Buffer.isBuffer(responseBody)).eql(true, logPrefix + 'Invalid response body (not buffer)');
// Periodic analytic id can be found on the server response of the 1st analytic sent.
return JSON.parse(logger.requests[0].response.body.toString()).id;
}
在此行
SyntaxError: Unexpected token in JSON at position 0
调试信息
本地http服务器的响应正文有效: localBuffer 转换为: localBufferToString
来自远程https服务器的响应正文失败: remoteBuffer 转换为: remoteBufferToString
问题
我想知道我用来将响应主体转换为json的方法是否正确。目前我使用:
return JSON.parse(logger.requests[0].response.body.toString()).id;
我的环境
JSON.parse(logger.requests[0].response.body.toString())
答案 0 :(得分:3)
我遇到了同样的问题,因为在我的情况下,服务器响应是压缩后的响应,并且 testcafe logger API不会自动解压缩响应。
所以我们遵循了以下步骤:
使用logResponseBody参数配置记录器(也如注释中所述,不要将'stringifyResponseBody'参数设置为true)
const logger = RequestLogger(
/yourApiRegex/,
{ logResponseBody: true },
);
编写一个帮助程序方法以解压缩请求正文:
import zlib from 'zlib';
export const getBody = async body => new Promise((resolve, reject) => {
zlib.gunzip(body, async (error, buff) => {
if (error !== null) {
return reject(error);
}
return resolve(JSON.parse(buff.toString()));
});
});
测试中的样本使用情况
await t.expect(logger.contains(
async (record) => {
const body = await (getBody(record.response.body));
return body.someProps === 'someValue';
},
)).ok();