【问题标题】:Change TestCafe RequestMock API response based on request body根据请求正文更改 TestCafe RequestMock API 响应
【发布时间】:2020-06-05 15:41:13
【问题描述】:

我正在使用 TestCafe Request Mock 功能来模拟 API 响应,如下所示。

export const deleteDocMock = (status = 200) =>
  RequestMock()
    .onRequestTo({
      url: /\/api\/my-api\/.*/,
      method: 'DELETE',
    })
    .respond({some response}, status, {
      'access-control-allow-credentials': 'true',
      'access-control-allow-methods': 'GET, POST, PUT, OPTIONS',
    });

我可以根据 URL 和方法类型过滤请求,但不能根据请求正文。 现在我有一个用例,如果请求正文不同,则同一 API 请求的 API 响应需要不同。 例如,如果 api 的请求正文如下所示,则响应正文会发生变化

{
id: 1
name: 'foo'
}

如果请求正文如下所示,响应将再次不同

{
id: 2
name: 'bar'
}

有什么方法可以根据请求正文过滤请求,以便可以使用 TestCafe 相应地更改响应? 任何帮助表示赞赏。

【问题讨论】:

    标签: typescript testing automated-tests e2e-testing testcafe


    【解决方案1】:

    您可以在onRequestTo 中使用谓词函数。我创建了一个简单的示例来演示它:

    import { RequestMock } from 'testcafe';
    
    fixture `Fixture`;
    
    const mock = RequestMock()
        .onRequestTo(request => {
            console.log(request); // The full request object
    
            return request.url.indexOf('google') > -1; // Here you can set your own rule
        })
        .respond((req, res) => {
            res.setBody('<html><body><h1>OK</h1></body></html>');
        });
    
    test
        .requestHooks(mock)
        ('test', async t => {
            await t
                .navigateTo('https://google.com')
                .debug(); // Here we can see our mocked response
        });
    

    【讨论】:

      【解决方案2】:

      有一个按谓词过滤的选项。 https://devexpress.github.io/testcafe/documentation/reference/test-api/requestmock/onrequestto.html#select-requests-to-be-handled-by-the-hook

      此页面上的其他过滤器有 requestMock 和 requestLogger 的示例,但谓词只有 requestLogger 的示例。无论如何,检查它是否有效。

      【讨论】:

      • 感谢@saurabh-shrivastava 的回复。我已经看过这个通过谓词过滤的文档,但无法找出使用它的正确方法。您是否见过任何相同的示例用法?
      【解决方案3】:

      感谢你们的帮助。这真的帮助了我。我现在可以根据请求正文过滤我的请求。我将 API 请求正文与我预期的 json 正文进行比较,并在条件通过时模拟响应。我的代码现在是这样的。我正在比较缓冲区,因为 request.body 属于 buffer 类型。

      const mock = RequestMock()
      .onRequestTo(
        request =>
          request.url.match(/api\/assets\/.*\/staged-document/) &&
          request.method === 'post' &&
          !Buffer.compare(request.body, Buffer.from({"assetId":1,"name":"file1.name"}, 'utf-8')),
      )
      .respond({some response}, status, {
        'access-control-allow-credentials': 'true',
        'access-control-allow-methods': 'GET, POST, PUT, OPTIONS',
      });
      

      【讨论】:

        猜你喜欢
        • 2021-09-04
        • 2017-06-19
        • 2018-07-09
        • 1970-01-01
        • 2021-03-31
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        • 1970-01-01
        相关资源
        最近更新 更多