Search code examples
typescripttestingautomated-testse2e-testingtestcafe

Change TestCafe RequestMock API response based on request body


I am using TestCafe Request Mock feature to mock API response as shown below.

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',
    });

I am able to filter the request based on the URL and Method type but not based on the request body. Now i have a use case where the API response needs to be different for the same API request if the request body is different. For example if the request body for the api is as shown below, the response body would change

{
id: 1
name: 'foo'
}

And if the request body is like shown below, the response would be again be different

{
id: 2
name: 'bar'
}

Is there any way to filter the request based on the request body so that the response can be changed accordingly with TestCafe? Any help is appreciated.


Solution

  • You can use a predicate function in your onRequestTo. I created a simple example to demonstrate it:

    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
        });