模拟 API 以根据请求 URL 的动态部分给出响应
Mock API to give response based on request URL's dynamic part
我想模拟 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.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);
});
我想模拟 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.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);
});