node.js - Jest 测试失败时如何打印请求和响应?

标签 node.js jestjs supertest

我正在使用 Supertest 和 Jest 来测试 Node.js API。

示例测试具有以下格式

it('Read a note for a user', (done) => {
      request(graphqlURL)
        .post('/graphql')
        .set(baseHeaders())
        .send({
          query: graphQLQuery
        })
        .end((err, res) => {
          expect(res.status).toBe(200);          
          done();
        })

    });

当前,当期望失败时,会记录以下内容

expect(received).toBe(expected) // Object.is equality

    Expected: 200
    Received: 404

我还想记录请求和响应以及失败的测试,以便在调试时获得更多上下文。

有没有办法只打印失败的测试?

最佳答案

expect 的工作方式是在期望失败时抛出 Error

Errormessage 属性是在测试报告中打印的内容。

我想,如果您想使用现有期望,并且只想使用附加数据来扩充失败消息,您可以捕获Error,将附加数据附加到message属性,然后再次抛出Error,如下所示:

it('Read a note for a user', (done) => {
  request(graphqlURL)
    .post('/graphql')
    .set(baseHeaders())
    .send({
      query: graphQLQuery
    })
    .end((err, res) => {
      try {
        expect(res.status).toBe(200);
      } catch (err) {
        // --- add additional data to the error message here ---
        err.message = `${err.message}\n\nfailing query: ${graphQLQuery}`;
        throw err;  // throw the error so test fails as expected
      }
      done();
    })
});

关于node.js - Jest 测试失败时如何打印请求和响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55095925/

相关文章:

typescript - 如何模拟包含正斜杠的模块?

javascript - 尝试通过模拟管道函数来测试文件检索

node.js - 使用 supertest 和 co 在请求后验证数据库内容

node.js - 我的 npm 模块应该安装在 Mac OS X 的什么位置?

node.js - 循环遍历集合中的文档以获取字段

javascript - 如何在托管 Web 服务器上实际部署 Node.js(或 django)项目?

javascript - 使用环境变量定义 PM2 脚本路径

node.js - 由于拆卸不当导致 Jest 测试泄漏

javascript - 如何测试 slim 的输入 react 性?

node.js - NodeJS 和 super 测试 : start tests with npm command