pupetter return svg as mock response - testing

I am using jsdom-screenshot for snapshot testing with puppeteer and I want to mock a response for a network request and render an svg that I have in my local files instead of the actual network request image.
In the jsdom-screenshot docs they have this piece of code to mock a network request but I don't know how to write in the request how to return the svg I have locally
generateImage({
intercept: request => {
if (request.url().endsWith(".svg")) {
// Fake a response
request.respond({
status: 200,
contentType: "image/svg+xml",
//how do i return the svg in the body ?
});
} else {
// Call request.continue() for requests which should not be intercepted
request.continue();
}
}
});
I would appreciate your help .

Related

Axios onUploadProgress jumps at 100% even before the request is done

I have a controller that calls multiple external api from Gmail API concurrently, and then saves the retrieved data into the database, all of this in ONE post request.
To start, I pooled the external api requests, map the results and save it to db.
In my Controller:
$resp = Http::pool(fn (Pool $pool) [
$pool->as('pool-1')->withToken($user->token)->get('https://....call-1');
$pool->as('pool-2')->withToken($user->token)->get('https://....call-2');
$pool->as('pool-3')->withToken($user->token)->get('https://....call-3');
]);
collect($resp)->map(function ($req) {
Email::firstOrCreate(...);
})
In my vue component:
const config = {
onUploadProgress: progressEvent => {
console.log(`sent: ${Math.floor((progressEvent.loaded * 100) / progressEvent.total)}`)
}
}
axios.post(url, param, config).then(response => {}).catch(err => {})
Now, when I check in console.
It should be logging:
sent:0
sent:1
sent:2
...
sent:100
But instead, it automatically logs sent:100 even though the post request is still pending.
Is this a bug in chrome? or axios?, or perhaps it has something to do with external api calls?
Or if it isn't, can someone point out where I went wrong?

Handling errors if no network is available

I just implemented my first backend file where I fetch some user data, messages and so on.
Now I wanted to include error handling if there is no network available.
I don´t know if I did it right but this was my approach so far:
import axios from 'axios'
const host = process.env.VUE_APP_URL
export default {
person: async function (currentPerson) {
let params = {
currentPerson: localStorage.getItem("person"),
};
if (user) {
params['currentPerson'] = currentPerson;
}
return axios.get(`${host}/api/currentPerson`, {
params: params
})
//catching network errors
.catch (error => {
if (error.response) {
/*
* The request was made and the server responded with a
4xx/5xx error
*/
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
/*
* The request was made but no response was received
*/
console.log(error.request);
} else {
// Something happened in setting up the request and triggered an Error
console.log('Error', error.message);
}
console.log(error)
});
},
In my mounted() function of my main view I fetch the data from my backend file from above:
backend.matches().then(function (response) {
self.contacts = response.data.persons;
});
I tried to check in console if it is working but all I get is the following:
In the catch block I check for
response errors: like 4xx/5xx
request errors: if my network not responding in time
and any other errors
Would this be the right approach to check if a network is available or not? Or does it degrade the user experience when the user checks the error?
My backend file includes more methods.. do I have to write for each method these kind of requests?
In your backend file you don't react whether there is a network connection or not I think.
And only for reference: that is not the backend, but communicates with the backend - the backend is the part of your code what you communicate with, e.g. Laravel code, an API, ...
Try adding the following at the beginning of your catch part:
if (!error.response) {
//network error
console.log('No network connection');
} else if (error.response) {
//the rest of your code
This should print out No network connection in your console.
Run your application, turn off the internet connection and check the console.
These kind of code should always be located in your backend part.
My answer maybe different from your question.
When i create a .net core API with Angular i used three things to check is there network or not?
subscribe to windows's offline/online event
create signalR hub from layout component to API server
API request failed (it means lot of incident, but if 1. or 2. case is true i know what cause 3. case

How to send an additional request to endpoint after each test case

I’m currently looking at Botium Box, and I’m wondering if it is possible to send an additional request to our endpoint after each test case? Let me give you some background information about how we set up the HTTP(S)/JSON connector in Botium Box and how we are sending information to our bot:
HTTP(S) endpoint:
https://MyChatBotsEndpoint.com/?userinput={{msg.messageText}}
HTTP method: POST
We also send cookies through the header template in the request builder. Like this:
{
"Cookie": "JSESSIONID={{context.sessionId}}"
}
The response is given back in JSON.
When a test ends (when it is successful but also when it fails), we need to send an additional request to our endpoint. The endpoint URL of that request should look like this:
https://MyChatBotsEndpoint.com/endsession
The header should include the cookie as described before.
Is there a way to achieve this in Botium?
Botium has many extension points to plug in your custom functionality. In this case, I guess the SIMPLEREST_STOP_HOOK is the best choice.
Write a small javascript file calling your endpoint, and register is with the SIMPLEREST_STOP_HOOK capability in botium.json. The context (session context from the HTTP/JSON connector) is part of the hook arguments.
in botium.json:
...
"SIMPLEREST_STOP_HOOK": "my-stop-hook.js"
...
my-stop-hook.js:
const request = require('request')
module.exports = ({ context }) => {
return new Promise((resolve, reject) => {
request({
method: 'GET',
uri: 'https://MyChatBotsEndpoint.com/endsession',
headers: {
Cookie: "JSESSIONID=" + context.sessionId
}
}, (err) => {
if (err) reject(err)
else resolve()
})
})
}

Stream api with fetch in a react-native app

I was trying to use Stream api with fetch in react-native app, I implemented with the help of a great example mentioned at jeakearchibald.com . code is something similar to :-
fetch('https://html.spec.whatwg.org/').then(function(response) {
console.log('response::-', response)
var reader = response.body.getReader();
var bytesReceived = 0;
reader.read().then(function processResult(result) {
if (result.done) {
console.log("Fetch complete");
return;
}
bytesReceived += result.value.length;
console.log(`Received ${bytesReceived} bytes of data so far`);
return reader.read().then(processResult);
});
});
Stream api reference is :-
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
But it seems fetch implementation of react-native is little different than of browsers and it is not easy to use Stream in the same way as used on web.
There is already an unresolved issue on react-native for the same
https://github.com/facebook/react-native/issues/12912
On web we can access Stream from response.body.getReader(), where response is just normal result retuned from fetch call of stream url, but in react-native there is no way we can access body and hence getReader from response of fetch call.
So to overcome this I tried to use rn-fetch-blob npm package , because it supports Streams, but that to seems to support only from locale file paths because there readStream functions doesn't seems to have support to pass Authorization and other necessary headers, so I tried to use RNFetchBlob.fetch with the remote url and necessary headers and then using readStream method from response but that always returns me there is no stream with the current response.
RNFetchBlob.fetch('GET', 'https://html.spec.whatwg.org/')
.progress((received, total) => {
console.log('progress', received / total);
})
.then((resp) => {
// const path = resp.path();
console.log('resp success:-', resp);
RNFetchBlob.fs.readStream(path, 'utf8').then((stream) => {
let data = '';
stream.open();
stream.onData((chunk) => {
data += chunk;
});
stream.onEnd(() => {
console.log('readStream::-', data);
});
// });
})
.catch((err) => {
console.log('trackAppointmentStatus::-', err);
});
I may be doing something wrong in both approaches of mine, so little guidance may help me or someone else in the future. Or I may need to find a way to do it natively with writing a bridge.

Make an http request on document load using cyclejs

How do I make an http request to a webservice on document load using cyclejs?
The examples cover reacting to user input and don't meet my needs.
You may try to create a request stream and pass it to the HTTPDriver.
For example:
const request$ = Rx.Observable.just({
url: 'http://www.google.com',
method: 'GET'
});
Then:
return {
HTTP: request$
};