Cypress: want to partially mock XHR response - cypress

I am using Cypress and I want to stub the XHR response partially. I want to catch the original JSON, and edit it partially.
for instance:
cy.route('GET', `**/subjects`, 'fixture:mySubjects.json');
this way i am stubbing the whole response, but I want to see:
original XHR response (of course with many other properties) :
{
'id': 12345,
"subjects": [
{
"key": "mat",
"name": "maths",
"hasAccess": true,
},
{
"key": "eng",
"name": "english",
"hasAccess": false,
}
],
}
what I want to stub is only name, and want to get:
{
'id': 12345,
"subjects": [
{
"key": "mat",
"name": "maths",
"hasAccess": true,
}
],
}
In short, what I wanted to do is to remove the second subject 'eng' from the response. any idea is much appreciated.

Take a look at cy.intercept().
I don't quite understand what parts of the real response you want to return or stub, but this is the mechanism to do so.
cy.intercept('/integrations', (req) => {
// req.reply() with a callback will send the request to the destination server
req.reply((res) => {
// 'res' represents the real destination response
// you can manipulate 'res' before it's sent to the browser
})
})
If you are using a Cypress version < 6 you can try using cy.route2() with the same syntax.

Related

VueJs not sending data via Inertia to Laravel?

I have question it seems like when I try to send some data via Inertia I dont recieve any in Laravel for some reason any suggestion? Can it have to do something with the fact that the object is proxy object ?
Here are some images:
dd() in php controlelr
console.log() of the object before beeing sent via Inertia
Code of how I send the data + the console log right before sending it
UPDATE:
This is how I add page object to array of pages:
this.Pages.push({
"name": "Untitled",
"icon": "home",
"order": order,
"sections": [],
"DisplayName":true,
"Banner":"Medium",
"Published":"Published",
"DisplayLogo":true,
"media":{
'BackgroundImage': null,
'LogoImage': null,
'BackgroundImageHeight': null,
'LogoImageHeight': null,
'BackgroundImageStyle': {
"value": []
},
"LogoImageStyle": {
"value": []
},
}
});
This is my inertia form:
saveForm: {
applications: [],
},
This is whole save() method:
Save() {
if(this.localProduct.translation.applications.mobile_label[this.currentMobileLabel] != undefined){
if(this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].data == undefined){
this.localProduct.translation.applications.mobile_label[this.currentMobileLabel] = {
"Pages": this.Pages,
"media": this.media,
"name": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].name,
"active": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].active,
};
}
else{
this.localProduct.translation.applications.mobile_label[this.currentMobileLabel] = {
"Pages": this.Pages,
"media": this.media,
"name": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].name,
"active": this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].active,
"data" : this.localProduct.translation.applications.mobile_label[this.currentMobileLabel].data,
};
}
}
this.saveForm.applications = toRaw(this.localProduct.translation.applications);
console.log(this.saveForm);
Inertia.post(this.route(`product.translations.applications`,{translation: this.localProduct.translation.id}),this.saveForm);
},
The applications should be array, the mobile_label should be also array.As it is.
!!!IMPORTANT ALSO!!!
All of this code worked before the project started to shift to vue js 3 and I suppose many libraries had to be updated/exchanged for others.
According to Inertia's documentation the first parameter expected when using Inertia.post() is a URL. Does all of this.route(`product.translations.applications`,{translation: thislocalProduct.translation.id}) return a URL?
To anyone who's having same problem check your array/object assiging to your variables there could be the mistake like in mine I fixed mine with this:
this.saveForm.applications = toRaw(this.localProduct.translation.applications);
var fixed = Object.assign({},this.localProduct.translation.applications);
Inertia.post(this.route(`product.translations.applications`,{translation: this.localProduct.translation.id}),fixed);

How to handle JSON array response while using APIConsumer?

Using the APIConsumer contract we can feed data from API to the smart contract.
Eg: If the server response is:
{
"RAW":{"ETH":{"USD":{"VOLUME24HOUR": 10000,}}}
}
Then, data can be obtained as:
request.add("get", URL);
request.add("path", "RAW.ETH.USD.VOLUME24HOUR");
Similarly, If the server response contains some JSON array,
Eg:
{
"date":"530934083405834",
"results": [
{
"id": 9865,
"rank":1
},
{
"id": 9869,
"rank": 2
},
{
"id": 9866,
"rank": 3
}
]}
Then in this case is there a way to get the id of the rank 1 i.e results[0]["id"]?
To get results[0]["id"] your path in the request needs to be
request.add("path", "results.0.id");

Retrieve contents of _source only- Elasticsearch ( Node JS)

According to Retrieving a document documentation
GET /website/blog/123/_source
would directly return the document stored inside the _source field.
I'm currently using Node JS's express framework. How should I implement this in my code?
esClient.search({
index: "myIndex",
type: "myType",
body: {
"query": {
"match_all": {}
},
"size": 3,
"from": 1
}
}).then(function (resp) {
var result = resp.hits.hits;
res.status(200).send({data: {recommendations: result, showItemFrom: showItemFrom}})
}, function (err) {
console.trace(err.message)
res.status(500).send({data: err.message})
})
I'm getting the response this way...
[
"_source":{
{
"id": 1,
"title": "Test"
}
}
]
However, I want it this way...
[
{
id:1,
title:"Test"
}
]
I don't think the Elasticsearch API has a method to do that for searches, the one that Val mentioned works, but it is only usable to GET documents directly through its id.
But you can map the result using the Javascript Array#map() method:
var result = resp.hits.hits.map(hit => hit._source);
After
index:"myIndex"
Add:
source:true
You need to call the getSource() function, like this:
esClient.getSource({
index: "website",
type: "blog",
id: "123"
}).then(function (source) {
// do something with source
}, function (err) {
// error happened
})

Unable to Properly Consume Data from $resource in Angular

I'm building a prototype app using Parse.com as a temporary backend.
This is how Parse structures its returned data when a request is made.
{
"results": [
{
"playerName": "Jang Min Chul",
"updatedAt": "2011-08-19T02:24:17.787Z",
"cheatMode": false,
"createdAt": "2011-08-19T02:24:17.787Z",
"objectId": "A22v5zRAgd",
"score": 80075
},
{
"playerName": "Sean Plott",
"updatedAt": "2011-08-21T18:02:52.248Z",
"cheatMode": false,
"createdAt": "2011-08-20T02:06:57.931Z",
"objectId": "Ed1nuqPvcm",
"score": 73453
}
]
}
I have a factory that looks like this
app.factory('eventFactory', ['$resource', function($resource){
return $resource('https://api.parse.com/1/classes/Events', {},
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:false},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'}
});
}
]);
My controller looks like this:
app.controller('currentTradeshowsController', function($scope, eventFactory){
var testSave = eventFactory.get();
console.log(testSave);
console.log(testSave.results);
});
the first console.log for 'testSave' looks like this :
Where as testSave.results returns undefined.
I would think that I would be able to access all the objects this way no?
What am I missing here?
Any help is very much appreciated.
Even though $resource does a very nice job of abstracting, the fact remains that since it works via HTTP calls it runs asynchronously and the code has to be written to handle that semantically. The documentation expresses this.
var testSave = eventFactory.get().success(function () {
console.log(testSave);
});
Unfortunately the Angular docs do not make it clear, but I think the above will work. Possible alternatives are:
.get(function () {
.get({}, function () {
.get().then(function () {
.get().$promise.then(function () {
Find one that works and works best for you. The idea is that the success callback and anything that relies on a successful request need to be in this function.

google-api-javascript-client : How to get contents of file using Drive API?

First off, if there is a question/answer that solves my problem already then I sincerely apologize for creating a new one. However, I have been searching for 3 days now, and have not found an answer...
My problem is, I cannot for the life of me figure out how to pull the contents of a file(any file). From reading the docs I've discovered that my returned file resource object is supposed to have a property named "downloadUrl", and from this I should be able to access the file contents.
None of the file resource objects that are returned to me(via gapi.client.request) have this field/property. Below is the function I am using to get a file.
Can someone please help point me in the right direction? I have to have this demo done by Monday and I've been stuck on this for 2 days....
Here is the code for my get function :
Client.getFileContent = function getFileContent() {
gapi.client.load('drive', 'v2', function() {
var request = gapi.client.request({
path : '/drive/v2/files/1QmaofXyVqnw6ODXHE5KWlUTcWbA9KkLyb-lBdh_FLUs',
method : 'GET',
params : {
projection: "FULL"
}
});
request.execute(function(response) {
console.log(response);
});
});
};
The file resource object that is returned to me does not have the downloadUrl property.
As requested, here is the response object I get back for a text file. Note, I replaced some of the ids with "fileid" for posting here.
"kind": "drive#file",
"id": "fileID",
"etag": "\"-tJAWr_lbRQU2o8gZ0X7BCBIlVk/MTM0MjYyODQ1MTQ2Nw\"",
"selfLink": "https://www.googleapis.com/drive/v2/files/fileID",
"alternateLink": "https://docs.google.com/document/d/fileID/edit",
"embedLink": "https://docs.google.com/document/d/fileID/preview",
"thumbnailLink": "https://docs.google.com/feeds/vt?gd=true&id=fileID&v=1&s=AMedNnoAAAAAUAfLhbYIDsNIn40k7DfRYBsrquijmCii&sz=s220",
"permissionsLink": "https://www.googleapis.com/drive/v2/files/fileID/permissions",
"title": "Copied filed.txt",
"mimeType": "application/vnd.google-apps.document",
"labels": {
"starred": false,
"hidden": false,
"trashed": false,
"restricted": false,
"viewed": true
},
"createdDate": "2012-07-18T16:20:51.132Z",
"modifiedDate": "2012-07-18T16:20:51.467Z",
"modifiedByMeDate": "2012-07-18T16:20:51.467Z",
"lastViewedByMeDate": "2012-07-18T16:20:51.467Z",
"parents": [
{
"kind": "drive#parentReference",
"id": "0AAAYYkwdgVqHUk9PVA",
"selfLink": "https://www.googleapis.com/drive/v2/files/fileID/parents/0AAAYYkwdgVqHUk9PVA",
"parentLink": "https://www.googleapis.com/drive/v2/files/0AAAYYkwdgVqHUk9PVA",
"isRoot": true
}
],
"exportLinks": {
"application/vnd.oasis.opendocument.text": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=odt",
"application/msword": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=doc",
"text/html": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=html",
"application/rtf": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=rtf",
"text/plain": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=txt",
"application/pdf": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=pdf"
},
"userPermission": {
"kind": "drive#permission",
"etag": "\"-tJAWr_lbRQU2o8gZ0X7BCBIlVk/9STkNeCmz61YXorH3hoJimnEgfM\"",
"id": "current",
"role": "owner",
"type": "user"
},
"quotaBytesUsed": "0",
"ownerNames": [
"Joshua.morine"
],
"lastModifyingUserName": "Joshua.morine",
"editable": true,
"writersCanShare": true
}
For native Google documents (Google Spreadsheet, Presentation etc...) we don;t provide a downloadUrl as these can't really be downloaded as files in their native format. Instead you'll have to use one of the URLs in the list of exportLinks which provides URLs to download the Google Documents in a few different export formats.
In your case, a Google Documents the following can be used:
"exportLinks": {
"application/vnd.oasis.opendocument.text": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=odt",
"application/msword": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=doc",
"text/html": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=html",
"application/rtf": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=rtf",
"text/plain": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=txt",
"application/pdf": "https://docs.google.com/feeds/download/documents/export/Export?id=fileID&exportFormat=pdf"
}
The meta-data function you are looking for is actually:
request = gapi.client.drive.files.get({
'fileId': fileId
});
This one produces a result with the downloadUrl that you're referring to. Then it's easy to grab the file using any HTTP request.

Resources