How do I can catch and modify XHR JSON response in cypress? - json

In Cypress there is possibility to stub XHR response, but I wanted to catch and modify JSON response.
https://docs.cypress.io/guides/guides/network-requests.html#Stub-Responses
https://docs.cypress.io/api/commands/route.html#With-Stubbing
I do not find a good example that explain this.
In my app there is a call to an API:
/isHuman
and response is:
{"isHuman":true}
I wanted to intercept this call and put true and another test with false
can anybody provide this ?
Last Edit:
Testing app in on localhost(where I define baseURL - localhost:3123), but there are api calls to a different domain(https://api.app.com/isHuman).
I need to change response from that xhr call.

You can redefine the same url multiple times inside the same it():
it('should od whatever', () => {
cy.route('GET', '/isHuman', { "isHuman": true });
/* trigger some requests */
cy.route('GET', '/isHuman', { "isHuman": false });
/* trigger other requests */
});

it('modifies the response from the server to insert Kiwi', () => {
cy.intercept('favorite-fruits', (req) => {
req.reply((res) => {
// add Kiwi to the list received from the server
console.log('original response from the server is %s %o', typeof res.body, res.body)
const list = res.body
list.push('Kiwi')
res.send(list)
})
})
cy.visit('/')
// check if Kiwi is the last fruit
cy.get('li').should('have.length.gt', 3)
.last().should('contain', 'Kiwi')
})
below is the source of the code:
Partial route mock

Related

I can't fill a request response using axios in state variable in React.js with Next.js

I'm working with React.js and I have the following problem:
import axios from "axios";
export default function Home() {
const [products, setProducts] = useState([]);
const ax = axios.create({ headers: { Accept: 'application/json' }});
function test() {
const res = ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search").then((response) => {
// expected the setProducts to be filled with the return of this request
setProducts(response.data);
});
}
test();
// and when I get here to see if the products have been filled, I get an empty array [ ]
console.log(products);
/*
as the products variable was not filled within the axios promise by setProducts,
there is no way to throw the products array here in the HTML to make a forEach or
a map to look cute together with the tags
*/
return (
<sup>how sad, with the product array empty, I can't put the data here '-'</sup>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
See how the result comes out in the IDE console:
I'm in Visual Studio not knowing what to do, I'm new to ReactJS with NextJS and from an early age I've been trying to see if I could solve this problem, but without success.
What can I do to bring the products to the HTML page?
UPDATE: As per the solution below, I created a possible workaround that indicates a path that could have returned a solution
ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search/", {})
.then((response) => setProducts(response.data))
.catch((error) => {
console.log(error); // AxiosError {message: 'Network Error', name: 'AxiosError', ...}
console.log(error.status); // undefined
console.log(error.code); // ERR_NETWORK
});
useEffect(() => {
console.log(products);
}, []);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.0.2/umd/react-dom.production.min.js"></script>
and I'm getting the same error that I put in the comments of the first answer below:
but when I change the setProducts by the console.log to see if it returns the same result, this appears in the terminal where my next.js application is running
that:
ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search/", {})
.then((response) => console.log(response.data.length)) // returns the length of the products array
returns this when I update my app:
NOTE: That's why I'm not able to understand my application in Next.js. I'm following all the correct guidelines, writing the code perfectly using axios and when I run the application on the website it gives a network error and doesn't show exactly the amount of products that were displayed in the terminal where my application is running.
I've already configured all the request headers correctly, enabling CORS to allow external requests with other API's, and I still don't succeed in returning the data to my application's page.
Wrap the stuff you have to fetch products inside useEffect hook
useEffect(()=>{
const ax = axios.create({ headers: { Accept: 'application/json' }});
function test() {
const res = ax.get("https://vtexstore.codeby.com.br/api/catalog_system/pub/products/search").then((response) => {
// expected the setProducts to be filled with the return of this request
setProducts(response.data);
console.log(response.data)
});
}
test();
},[])
Then in your return of the component, you can use map on products array with null and undefined checks
Like
{products && products.map(product=>{})}

fetch to Wikipedia-api is not being made

I'm doing the wikipedia viewer from FCC projects with React, Im trying to make the request by just passing it the searchQuery (from my state) with template string. Like this:
gettingArticle() {
const { searchQuery, articlesList } = this.state;
const API = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${searchQuery}&prop=info&inprop=url&utf8=&format=json`;
const body = { method: 'GET', dataType: 'json'};
const myRequest = new Request(API, body);
fetch(myRequest)
.then(response => response.json())
.then(data => this.setState({
articlesList: data, articles: true }));
console.log( 'data fetched' + displayedArticles);
}
I don't know for sure if is like this that I have to made the request it's just what I saw on the docs. I want to made the request and after receive the data I want to iterate over the array of objects and put every little thing that I need in their corresponding tag inside a div. Here is my entire code: https://codepen.io/manAbl/pen/VxQQyJ?editors=0110
The issue is because you missed a key details in the API documentation
https://www.mediawiki.org/wiki/API:Cross-site_requests
Unauthenticated CORS requests may be made from any origin by setting the "origin" request parameter to "*". In this case MediaWiki will include the Access-Control-Allow-Credentials: false header in the response and will process the request as if logged out (in case credentials are somehow sent anyway).
So I update your url like below
const API = `https://en.wikipedia.org/w/api.php?action=query&origin=*&list=search&srsearch=${searchQuery}&prop=info&inprop=url&utf8=&format=json`;
And also your console.log was at the wrong place, so I changed it to below
fetch(myRequest)
.then(response => response.json())
.then(data => {
console.log( 'data fetched', data);
this.setState({
articlesList: data, articles: true })
});
Below is a updates pen
https://codepen.io/anon/pen/BxMyxX?editors=0110
And now you can see the API call works
Of course I didn't check why you have white strip after the call is successful, but that may be something wrong you do in your React code
The problem is not really in your code but in CORS, basically you are not allowed to make the call because of same origin policy.
Change these 2 constants
const API = `https://crossorigin.me/https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${searchQuery}&prop=info&inprop=url&utf8=&format=json`;
const body = { method: 'GET', dataType: 'json', mode: 'cors', cache: 'default'};
I added crossorigin url before your API because it 'overrides' CORS and enables you to make calls outside the same origin policy. You should also modify your submit function:
handleSubmit(ev) {
ev.preventDefault(); //This disables default form function (reload/redirect of website and loss of state)
this.gettingArticle();
}

Understanding the streaming concept in node.js

I am trying to convert a CSV data to JSON data while streaming from a HTTP url by using "csvtojson" package.
const csv = require("csvtojson");
const request = require('request');
let options = {
uri: '',
****
};
let tempArr = [];
csv()
.fromStream(request(options))
.on("json", (jsonObj) => {
if (JSON.parse(jsonObj.Response).intents[0].intent == "None")
tempArr.push(JSON.parse(jsonObj.Response));
})
.on('done', (error) => {
callback(null, tempArr)
})
This is calling under an API. When I starts the server and call this api to convert csv to json, it works perfectly.
And If I call the same API again, the "json" event is not getting triggered, Instead "done" event is triggered directly.
i.e., the streaming is not done from the second time. why is it behaving like this?
and what should I do to solve this problem?

Angular http post not working 1st time, but works on 2nd time

Trying my first angular exercise. Receiving undefined value on 1st time from http post, but 2nd time getting proper response (Edge, Firefox). Thanks!
LoginService (Calls Http post method and returns observable)
login(loginRequest: LoginRequest){
console.log("LoginService.login - userName " + loginRequest.username);
let options = new RequestOptions({ headers: headers });
return this.http.post(this.http_url, loginRequest, options).map( res =>
res.json());
LoginFormComponent (calls service class and convert JSON to typescript object)
onSubmit() {
this.loginSvc.login(this.loginRequest).subscribe(
data => this.loginResponseStr = data,
error => alert(error),
() => console.log('Request completed')
);
var loginResponse = new LoginResponse();
loginResponse.fillFromJSON(JSON.stringify(this.loginResponseStr));
console.log(loginResponse.status);
console.log(loginResponse.statusDesc);
if(loginResponse.status == "SUCCESS"){
this.router.navigate(['/home-page']);
}
Console log
LoginService.login - userName admin main.bundle.js:370:9
undefined main.bundle.js:266:9
undefined main.bundle.js:267:9
Request completed main.bundle.js:263:181
LoginService.login - userName admin main.bundle.js:370:9
SUCCESS main.bundle.js:266:9
VALID USER main.bundle.js:267:9
Request completed main.bundle.js:263:181
Angular server calls are asynchronous, that mean the code wont wait for the server to respond before executing the rest of the code. Such as PHP. So you would not see a blank page waiting for the server to send data. When you want to deal with the respose come from a server call you have to add all the code within the subscribe; that means if this information needed to be passed to another service.
Your code should look like this.
onSubmit() {
this.loginSvc.login(this.loginRequest).subscribe(
data => {
this.loginResponseStr = data
var loginResponse = new LoginResponse();
loginResponse.fillFromJSON(JSON.stringify(data));
console.log(loginResponse.status);
console.log(loginResponse.statusDesc);
if (loginResponse.status == "SUCCESS") {
this.router.navigate(['/home-page']);
}
},
error => alert(error),
() => console.log('Request completed')
);
}

Node Express 4 get header in middleware missing

I have a middleware function using Node's Express4 to log each request & response for debugging. I use the res.json call in the request handler to send back JSON to the client for all but static files. So I do not want to log the response for static files, but only the JSON responses. I have the following code:
function logRequests(req, res, next) {
// do logging (will show user name before authentication)
logger.reqLog('IN '+req.method+' '+req.url, req);
var oldEnd = res.end,
oldWrite = res.write,
chunks = [];
res.write = function(chunk) {
chunks.push(chunk);
oldWrite.apply(res, arguments);
};
res.end = function(chunk, encoding) {
if(chunk) {
chunks.push(chunk);
}
oldEnd.apply(res, arguments);
// the content-type prints "undefined" in some cases
// even though the browser shows it returned as "application/json"
console.log('type='+res.get('content-type'));
if(res.get('content-type') === 'application/json') {
var body = Buffer.concat(chunks).toString('utf8');
logger.info(body, req);
}
logger.reqLog('OUT '+req.method+' '+req.path, req);
};
next(); // make sure we go to the next routes and don't stop here
}
So why do some requests show the correct content type in the middleware meaning they also print the response fine and others do not? All of them look good in the REST client when inspecting the returned headers.
EDIT: Some more info discovered tonight while trying to figure this out - if I append any character as a dummy request parameter, it logs the response type correctly:
http://localhost:8081/node/ionmed/api/logout?0 WORKS
where
http://localhost:8081/node/ionmed/api/logout DOES NOT
Also, I can always get a response type logging in the middleware function if I replace the .json() call with .end() so this:
res.json({ item: 'logout', success: true });
becomes:
res.set('content-type', 'application/json');
res.end({ item: 'logout', success: true });