【问题标题】:Mock API to give response based on request URL's dynamic part模拟 API 根据请求 URL 的动态部分给出响应
【发布时间】:2019-07-12 07:34:51
【问题描述】:
我想模拟 API 调用,以便
请求
http://localhost:8080/api/test/<yyyy-mm-dd>
给出回应:
{date: <yyyy-mm-dd>, data: 'my cool data'}
其中<yyyy-mm-dd> 不固定(此请求在过去 7 天内发出 7 次)
如何在 TestCafé 中为此创建模拟?请注意,响应数据取决于请求 URL。
【问题讨论】:
标签:
automated-tests
httprequest
e2e-testing
web-testing
testcafe
【解决方案1】:
将index.html 和index.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);
});