How is it possible to use a mock server for JSON REST API and not for a oData service? I would like to mock http://localhost:8080/api/v1/configs to get a JSON list of all configurations even if I have no backend connection and I am running the app in mock mode.
The following is not working, it returns furthermore the real data and not the mocked data.
mockserver.js:
sap.ui.define([
"sap/ui/core/util/MockServer",
"sap/base/util/UriParameters"
], function (MockServer, UriParameters) {
"use strict";
var oTokenRequest = {
method: "GET",
path: new RegExp("/actuator/info"),
response: function (oXhr, sNodeId) {
jQuery.sap.log.debug("Incoming request for X-CSRF Token");
oXhr.respondJSON(200, {
"X-Csrf-Token": "myFakeToken"
}, {});
}
};
var oMockServer;
return {
init: function () {
var oUriParameters = new UriParameters(window.location.href);
// configure mock server with a delay
MockServer.config({
autoRespond: true,
autoRespondAfter: oUriParameters.get("serverDelay") || 500
});
var oAllConfigurations = {
method: "GET",
path: "/configs", // or "new RegExp(".*?")" for everything after v1/?
response: function (oXhr, sUrlParams) {
oXhr.respondJSON(200, {}, JSON.stringify({
"uuid": "50df30x9-762b-341c-9881-7315l242b6c5",
"name": "Config1",
"description": "Mapping for component1",
"fileVersion": 3,
"createdAt": 1581517043000,
"updatedAt": 1589039157000
}, {
"uuid": "4f68da04-28a2-4a4e-947k-6d7be70cr03k",
"name": "MOCKSERVER-Config2",
"description": "Mapping for component2",
"fileVersion": 12,
"createdAt": 1553685823000,
"updatedAt": 1589363607000
}, {
"uuid": "6g6chg1-23a2-4a3o-332a-2a6be08ca02f",
"name": "Config3",
"description": "Mapping for component3",
"fileVersion": 1,
"createdAt": 1596119686000,
"updatedAt": 1596119686000
}));
}
};
var aRequests = [oTokenRequest];
aRequests = aRequests.concat(oAllConfigurations);
// create
this.oMockServer = new MockServer({
rootUri: "http://localhost:8080/api/v1",
requests: [oAllConfigurations]
});
// start
this.oMockServer.start();
}
};
});
data-sap-ui-oninit in mockServer.html leads to initMockServer.js
initMockServer.js:
sap.ui.define([
"../localService/mockserver"
], function (mockserver) {
"use strict";
// initialize the mock server
mockserver.init();
// initialize the embedded component on the HTML page
sap.ui.require(["sap/ui/core/ComponentSupport"]);
});
Main.controller.js:
//...
_getConfigList: function () {
var oModelConfigList = new JSONModel();
this.request = new BaseRequests();
return fetch("http://localhost:8080/api/v1/configs")
.then((response) => {
if (response.ok) {
return response.json();
} else {
MessageToast.show(response.statusText);
return null;
}
}).then(json => {
if (json) {
oModelConfigList.setData(json);
this.getView().setModel(oModelConfigList, "ConfigList");
}
});
},
//...