Search code examples
automated-testshttprequeste2e-testingweb-testingtestcafe

Mock API to give response based on request URL's dynamic part


I would like to mock API calls so that request to http://localhost:8080/api/test/<yyyy-mm-dd> gives a response: {date: <yyyy-mm-dd>, data: 'my cool data'} where <yyyy-mm-dd> is not fixed (This request is made 7 times for last 7 days)

How can I create a mock for this in TestCafé? Note that response data depends on the request URL.


Solution

  • Place index.html and index.js files in the same folder. Then run testcafe chrome test.js command in your terminal.

    index.html

    <html>
        <body>
            <h1>Page</h1>
            <button id="sendRequestBtn">Send request</button>
            <code id='response'></code>
            <script>
                var sendRequestBtn = document.getElementById('sendRequestBtn');
                var responseData   = document.getElementById('response');
    
                sendRequestBtn.addEventListener('click', function (){
                    fetch('http://localhost:8080/api/test/2019-07-12')
                        .then(response => {
                             return response.json();
                        })
                        .then(json => {
                             responseData.textContent = JSON.stringify(json, null, 4);
                        })
                        .catch(e => console.error(e));
                });
            </script>
        </body>
    </html>
    
    

    test.js

    import { RequestMock } from 'testcafe';
    
    const mock = RequestMock()
        .onRequestTo(/http:\/\/localhost:8080\/api\/test\/.*/)
        .respond((req, res) => {
            res.headers['access-control-allow-origin'] = '*'; // It's necessary because TestCafe load the page via file protocol in this example.
    
            const dateUrlPart = req.path.replace('/api/test/', '');
    
            res.setBody({
                date: dateUrlPart, 
                data: 'my cool data'
            });
        });
    
    fixture `Fixture`
        .page('./index.html')
        .requestHooks(mock);
    
    test('test', async t => {
        await t.click('#sendRequestBtn').wait(1000);
    });