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

标签 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。

最佳答案

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

关于automated-tests - 模拟 API 根据请求 URL 的动态部分给出响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57002221/

相关文章:

javascript - 使用Protractor进行AngularJS测试-使用browser.wait()

docker - 当testcafe在docker容器中运行时,如何访问在localhost中运行的应用程序?

testing - Testcafe 测试未在 MacBook Big Sur 上执行,带有 UnableToAccessScreenRecordingAPIError :

javascript - 如何用 nightwatch.js 和 sinon.js 模拟 API 响应?

Android 数据库 - 没有这样的表错误

javascript - 如何使用 wdio.conf.js 文件指定要运行的 e2e 测试的测试文件夹?

linux - 在 gitlab CI 中,gitlab runner 选择了错误的执行器

c# - 免费或开源WinForms UI抓取/自动化库

python - 在Python中使用 'requests'模块发出POST请求

ssl - Http通过socks5获取请求| EOF错误