Kum*_*rav 2 automated-tests web-testing httprequest e2e-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.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>
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)