Search code examples
resttestingautomated-testse2e-testingtestcafe

Does testcafe support testing of rest api


Tests hang in the testcafe browser when you try to test a rest api url directly.

I am trying to run a test against my rest API endpoint using request hooks, but when I run the test from the command line, the browser opens the API endpoint and loads it and hangs. The test doesn't pass or fail and hangs. The rest API endpoint just returns a JSON response.


const logger = RequestLogger('https://example.com/search/suggestions?search=testkeyword');

fixture `test`
    .page('https://example.com/search/suggestions?search=testkeyword');

test
    .requestHooks(logger)
    ('test', async t => {

        // Ensure that the response has been received and that its status code is 200.
        await t.expect(logger.contains(record => record.response.statusCode === 200)).ok();

        const logRecord = logger.requests[0];

        console.log(logRecord.userAgent);           
        console.log(logRecord.request.url);         
        console.log(logRecord.request.method);      
        console.log(logRecord.response.statusCode); 
    });

I expect the test to pass checking for 200 status code, but the test hangs without showing pass/fail. Does testcafe support testing of rest API endpoints? I have checked this issue - https://github.com/DevExpress/testcafe/issues/1471 where it says testcafe doesn't support non-html pages. Please confirm.


Solution

  • You are right, TestCafe is intended to work with html pages, but it will use the "about:blank" page if you don't define any url. You can use the regular node.js HTTP API without request hooks for this case. Look at the following example:

    import http from 'http';
    
    const getResponseData = (url) => new Promise((resolve, reject) => {
        http.get(url, res => {
            const { statusCode } = res;
            const contentType = res.headers['content-type'];
    
            res.setEncoding('utf8');
            let rawData = '';
            res.on('data', (chunk) => { rawData += chunk; });
            res.on('end', () => resolve({ statusCode, contentType, rawData }));
        }).on('error', e => reject(e));
    });
    
    fixture `Test REST API`;
    
    test('Simple Test', async t => {
        const response = await getResponseData('http://example.com/api/1');
        await t
            .expect(response.statusCode).eql(200);
    });