模拟API以根据请求URL的动态部分给出响应

时间:2019-07-12 07:34:51

标签: automated-tests httprequest e2e-testing web-testing testcafe

我想模拟API调用,以便 请求 http://localhost:8080/api/test/<yyyy-mm-dd> 给出响应: {date: <yyyy-mm-dd>, data: 'my cool data'} <yyyy-mm-dd>不固定的位置(此请求在过去7天中进行了7次)

如何在TestCafé中为此创建模拟?请注意,响应数据取决于请求URL。

1 个答案:

答案 0 :(得分:5)

index.htmlindex.js文件放在同一文件夹中。然后在您的终端中运行testcafe chrome test.js命令。

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