node.js - 如何获取 RequestLogger 的 json 响应

标签 node.js testing automated-tests e2e-testing testcafe

RequestLogger

A 在主测试 Controller 之外进行此测试,使用 page modelthis食谱。

/**
  Used to get the periodic analytic id.
  Whenever we are viewing an asset, the 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;
}

错误

针对本地 Http 服务器运行此测试时,工作正常。但是当测试针对 https 远程服务器时它会失败。我收到此错误:

SyntaxError: Unexpected token  in JSON at position 0

在这条线上

return JSON.parse(logger.requests[0].response.body.toString()).id;

调试信息

来自有效的本地 Http 服务器的响应正文: localBuffer 它翻译成: localBufferToString

来自失败的远程 https 服务器的响应正文: remoteBuffer 它翻译成: remoteBufferToString

问题

我想知道我用来将响应体转换为 json 的方法是否可以。目前我使用:

JSON.parse(logger.requests[0].response.body.toString())

我的环境

operating system: Windows 10
testcafe version: 0.21.1
node.js version: 9.3.0

最佳答案

我有同样的问题,因为在我的例子中服务器响应是一个gzipped 响应,并且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();

关于node.js - 如何获取 RequestLogger 的 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51972855/

相关文章:

java - 流数据解决方案(Java、Python、socket.io、Node JS)

angularjs - 系统时间更改后 JWT 刷新

testing - 测试是 Scrum 的重要组成部分吗?

c# - 调用 .NavigateToUrl(Uri uri) 时 BrowserWindow.Uri 属性未更新

java - 在 Selenium Webdriver (Java) 中断言整数值

node.js - 生成可执行文件时 Docker-compose EACCESS 错误

javascript - Kik 卡 - 我可以导入/需要 Kik.js 文件吗?

grails - 如何在 Grails 应用程序中运行 Geb 测试套件

ruby - 无法使用 Selenium cucumber 通过 capybara 点击评级图像

python - 如何在 window x64 上用 python 记录 selenium webdriver 测试执行