JanOfPrague
JanOfPrague

Reputation: 31

Testcafe checking api response always passes

I have a testcafe test that checks API response JSON for a matching string and no matter what is in the response JSON, the test always passed.

I am running Gherkin/Testcafe integration. Last "Then" step is to check an API response JSON body.

logger = RequestLogger(config.serverUrl + '/api/v1/service', {
        logResponseHeaders: true,
        logResponseBody: true,
    });
    await t
        .addRequestHooks(logger)
        .navigateTo(config.serverUrl + '/admin/integrations')
        .expect(logger.contains(record => record.response.statusCode === 200))
        .ok();

    await t
        .expect(
            logger.contains(async record => {
                // console.log(record.response.headers);
                const body =
                    record.response.headers['content-encoding'] === 'gzip'
                        ? await getBody(record.response.body)
                        : record.response.body.toString();
                const bodyJson = JSON.parse(body);
                return bodyJson.filter(node => node.title === "Devtest").length == 1;
            })
        )
        .ok();

In the end, the code should return true/false depending on finding/not finding at least one item containing "Devtest".

However, the test always passes no matter what is the number.

Upvotes: 3

Views: 907

Answers (1)

mlosev
mlosev

Reputation: 5227

RequestLogger doesn't support the async function for the predicate parameter of the containsfunction. So, this expectation always passes - await t.expect(logger.contains(async record => false)).ok(). To fix the problem I suggest you split your code into two pars:

const record = request.records.find(r => ...);
const body = record.response.headers['content-encoding'] === 'gzip'
             ? await getBody(record.response.body)
             : record.response.body.toString();

const bodyJson = JSON.parse(body);

await t.expect(bodyJson.filter(node => node.title === "Devtest").length === 1).ok();

I also see that the capability to automatically unzip response bodies can simplify your test code. If you have time you can try to implement this feature and open a pull request in the TestCafe repository.

Upvotes: 2

Related Questions