Debugging Sinon.js in some smart way - sinon

We're using Sinon.JS for some integration-ish testing and I'm having a problem I need to debug somehow. We're using the fakeServer.create() method like so:
server = Sinon.fakeServer.create()
server.autoRespond = true
server.respondWith "GET", ...
Normally when working with xhr, you just open the network-tab in chrome dev tools and you can see all calls to the server, the order of them and the responses from the server. This is super helpful for debugging. Can I achieve something similar when working with Sinon?

If you are using karma-runner in a browser such as Google Chrome, you can use the "debug" feature. The general idea is starting the karma test with runonce disabled, and then clicking the debug button on the browser window that pops up. You can set breakpoints and debug the tests in a web browser like you normally would, including opening up the network tab in chrome.

The documentation in this area is a little sparse, but one of the configuration options for Sinon's createFakeServer() is logger, here's an example of how you might use it:
var server = sinon.createFakeServer({ logger: console.log });
This will produce:
Request:
[FakeXMLHttpRequest] {
async: true,
errorFlag: false,
eventListeners: {
abort: [function () {}],
error: [function () {}],
load: [function () {}],
loadend: [function () {}],
loadstart: [function () {}],
progress: [function () {}],
timeout: [function () {}]
},
logError: function logError() {},
method: "GET",
onSend: function () {},
onerror: function () {},
onload: function () {},
onreadystatechange: function () {},
password: undefined,
readyState: 1,
requestBody: null,
requestHeaders: {
Accept: "application/json, text/javascript, */*; q=0.01",
Content-Type: "text/plain;charset=utf-8",
X-Requested-With: "XMLHttpRequest",
twProjectsVer: "2.0"
},
response: (empty string),
responseText: (empty string),
responseType: (empty string),
responseXML: null,
sendFlag: true,
status: 0,
statusText: (empty string),
timeout: 0,
unsafeHeadersEnabled: function () {},
upload: {
eventListeners: {
abort: [function () {}],
error: [function () {}],
load: [function () {}],
loadend: [function () {}],
loadstart: [function () {}],
progress: [function () {}],
timeout: [function () {}]
}
},
url: "/entities.json?page=1&pageSize=50&offsetCount=0",
username: undefined,
withCredentials: false
}
Response:
[404, { }, (empty string)]

Adding some more details to #dustinroepsch answer.
Start Karma with these options
karma start karma.conf.js --browsers=Chrome --single-run=false --debug
This will open up a Google Chrome instance that does not get closed once test completes. You should be able to view both the source and test files in Developer Tools -> Source. You can then place breakpoints and reload the page to debug.

Related

Supabase JS reponse no data property

I tried to configure a next js project with supabase
But the data I receive is not consistent
To do this I have configured the following 3 files :
.env.local
NEXT_PUBLIC_SUPABASE_URL= ********
NEXT_PUBLIC_SUPABASE_ANON_KEY= ********
supabase.js
import { createClient } from '#supabase/supabase-js'
const supabase = createClient(
process.env.NEXT_PUBLIC_SUPABASE_URL,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
)
export default supabase;
pages/api/posts.js
import supabase from '../../utils/supabase';
export default function handler(req, res) {
const posts = supabase.from("posts").select("*");
res.status(200).json(posts);
}
When I console log my posts variable, I have no data property.
It returned this,
PostgrestFilterBuilder {
fetch: [Function (anonymous)],
shouldThrowOnError: false,
allowEmpty: false,
url: URL {
href: '********/rest/v1/posts?select=*',
origin: '********',
protocol: 'https:',
username: '',
password: '',
host: '********',
hostname: '********',
port: '',
pathname: '/rest/v1/posts',
search: '?select=*',
searchParams: URLSearchParams { 'select' => '*' },
hash: ''
},
headers: {
'X-Client-Info': 'supabase-js/1.35.4',
apikey: '********',
Authorization: 'Bearer ********'
},
schema: 'public',
_subscription: null,
_realtime: RealtimeClient {
accessToken: null,
channels: [],
endPoint: 'wss://********/realtime/v1/websocket',
headers: { 'X-Client-Info': 'supabase-js/1.35.4' },
params: {
apikey: '********'
},
timeout: 10000,
transport: [Function: W3CWebSocket],
heartbeatIntervalMs: 30000,
longpollerTimeout: 20000,
heartbeatTimer: undefined,
pendingHeartbeatRef: null,
ref: 0,
logger: [Function: noop],
conn: null,
sendBuffer: [],
serializer: Serializer { HEADER_LENGTH: 1 },
stateChangeCallbacks: { open: [], close: [], error: [], message: [] },
reconnectAfterMs: [Function (anonymous)],
encode: [Function (anonymous)],
decode: [Function: bound decode],
reconnectTimer: Timer {
callback: [Function (anonymous)],
timerCalc: [Function (anonymous)],
timer: undefined,
tries: 0
}
},
_headers: {
'X-Client-Info': 'supabase-js/1.35.4',
apikey: '********',
Authorization: 'Bearer ********'
},
_schema: 'public',
_table: 'posts',
method: 'GET',
cs: [Function: contains],
cd: [Function: containedBy],
sl: [Function: rangeLt],
sr: [Function: rangeGt],
nxl: [Function: rangeGte],
nxr: [Function: rangeLte],
adj: [Function: rangeAdjacent],
ov: [Function: overlaps]
}
Also when I look at the dashboard of my supabase database I see that no query is receive
It seems that this query is not sent to the supabase API but I have no idea why ?
You need to await the Promise: https://supabase.com/docs/reference/javascript/select
import supabase from '../../utils/supabase';
export default async function handler(req, res) {
const posts = await supabase.from("posts").select("*");
res.status(200).json(posts);
}

Invalid patch error in Contentful CMA client

I am trying to populating an empty field by using patch method in Contentful. The following piece of code works in one cloned environment but does not work in another.
let patchData: OpPatch[] = [
{
op: 'replace',
path: '/fields/keywords',
value: entryKeyword,
},
];
await cmaClient.entry.patch({ entryId: entryId }, patchData, { 'X-Contentful-Version': entryVersion });
When I try to execute this, receiving a 'Unprocessable Entity' error:
UnprocessableEntity: {
"status": 422,
"statusText": "Unprocessable Entity",
"message": "Could not apply patch to entry: invalid patch",
"details": {},
"request": {
"url": "/spaces/xyz/environments/abc/entries/123456789",
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json-patch+json",
"X-Contentful-User-Agent": "sdk contentful-management-plain.js/7.54.2;",
"Authorization": "Bearer ...",
"user-agent": "node.js/v14.19.2",
"Accept-Encoding": "gzip",
"X-Contentful-Version": 25,
"Content-Length": 78
},
"method": "patch",
"payloadData": "[{\"op\":\"replace\",\"path\":\"/fields/keywords\",\"value\":\"test keyword\"}]"
},
"requestId": "abcd-123456"
}
I have the same exact access permissions to both environments. What am I missing out on?
I had the same issue - turned out when the entry doesn't have the filed you're trying to patch - it will throw an error like above.

Getting a fetch error using redux toolkit and RTK-Query

I am using RTK-Query, and Redux-toolkit for this app, and I created an api-slice with createApi, as per the docs.
When I run a request to the backend, I get a "FETCH_ERROR"; however, when I run the same request using Axios, I get the data correctly from the backend, which leads me to believe I have an error in my code. I am just not sure where exactly it is.
Here is the error:
Object {
"api": Object {
"config": Object {
"focused": true,
"keepUnusedDataFor": 60,
"middlewareRegistered": true,
"online": true,
"reducerPath": "api",
"refetchOnFocus": false,
"refetchOnMountOrArgChange": false,
"refetchOnReconnect": false,
},
"mutations": Object {},
"provided": Object {},
"queries": Object {
"test(undefined)": Object {
"endpointName": "test",
"error": Object {
"error": "TypeError: Network request failed",
"status": "FETCH_ERROR",
},
"requestId": "BWOuLpOxoDKTzlUYFLW4x",
"startedTimeStamp": 1643667104869,
"status": "rejected",
},
},
"subscriptions": Object {
"test(undefined)": Object {
"QJSCV641RznGWyudGWuMb": Object {
"pollingInterval": 0,
"refetchOnFocus": undefined,
"refetchOnReconnect": undefined,
},
},
},
},
"test": Object {
"data": Array [],
},
}
Here is the test slice:
import { createSlice } from "#reduxjs/toolkit";
const testSlice = createSlice({
name: "test",
initialState: {
data: [],
},
reducers: {
getData: (state) => {
state;
},
},
});
export const { getData } = testSlice.actions;
export default testSlice.reducer;
Here is the apiSlice:
import { createApi, fetchBaseQuery } from "#reduxjs/toolkit/query/react";
export const apiSice = createApi({
reducerPath: "test",
baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_backend_url }),
endpoints: (builder) => ({
test: builder.query({
query: () => "/test",
}),
}),
});
export const { useTestQuery } = apiSice;
I solved it by changing the backend URL to my current ipv4 (for expo development, otherwise just your whatever your backend URL is) address in my .env file, then deleting cache, and restarting my app. In my case I was using expo so, expo r -c, and it worked.

request-promise not recognizing the URI when it is stated in the option object

I have a method that should return a response from another server. I use request-promise and put the URL in the options object.
As you can see in the code below, all is in good shape, but when I send the request, it returns 404 - resource not found.
When I change the request(options) method with request("https://api.quickpay.net/payments"), I get a positive answer from the server -- it tells me to add headers and so forth, which is positive.
public requestNewQuickpayPayment(order_id: String, currency : String, callback: Function) {
var options = {
method: 'POST',
uri: 'https://api.quickpay.net/payments',
form:{
order_id : "order123",
currency : "dkk"
},
headers: {
"Content-Type" : "application/json",
'Accept-Version': 'v10'
},
json: true
};
request(options).then((response:any)=>{
console.log(response);
return response;
}).catch((error:any)=>{
console.log(error);
return error;
}).finally(()=>{
console.log("done");
})
}
Something from the console
Request {
_events: [Object],
_eventsCount: 5,
_maxListeners: undefined,
method: 'POST',
uri: [Url],
transform2xxOnly: true,
headers: [Object],
readable: true,
writable: true,
explicitMethod: true,
_qs: [Querystring],
_auth: [Auth],
_oauth: [OAuth],
_multipart: [Multipart],
_redirect: [Redirect],
_tunnel: [Tunnel],
_rp_resolve: [Function],
_rp_reject: [Function],
_rp_promise: [Promise],
_rp_callbackOrig: undefined,
callback: [Function],
_rp_options: [Object],
setHeader: [Function],
hasHeader: [Function],
getHeader: [Function],
removeHeader: [Function],
localAddress: undefined,
pool: {},
dests: [],
__isRequestRequest: true,
_callback: [Function: RP$callback],
proxy: null,
tunnel: true,
setHost: true,
originalCookieHeader: undefined,
_disableCookies: true,
_jar: undefined,
port: 443,
host: 'api.quickpay.net',
body: 'order_id=asdasdasd&currency=dkk',
path: '/payments',
_json: true,
httpModule: [Object],
agentClass: [Function],
agent: [Agent],
_started: true,
href: 'https://api.quickpay.net/payments',
req: [ClientRequest],
ntick: true,
response: [Circular],
originalHost: 'api.quickpay.net',
originalHostHeaderName: 'host',
responseContent: [Circular],
_destdata: true,
_ended: true,
_callbackCalled: true },
toJSON: [Function: responseToJSON],
caseless: Caseless { dict: [Object] },
body: '404 Not Found' } }
What is wrong here? The path to the ressource is checked many times - nothing is wrong there....
For api.quickpay.net, 404 Not Found does not mean the URI is not recognized, but indicating invalid request body. It has nothing to do with whether the URI is stated in options object, or stated as string parameter of request().
Here is a simple experiment. The code below would return "positive" result, warning missing headers ({"error":"Accept-Version http header is required"}), which indicates that the URI is "recognized":
request({
method: 'POST',
uri: 'https://api.quickpay.net/payments'
}, function(err, res, body) {
console.log(body);
});
However, after the missing Accept-Version header is added, we get 404 Not Found:
request({
method: 'POST',
uri: 'https://api.quickpay.net/payments',
headers: {
'Accept-Version': 'v10'
}
}, function(err, res, body) {
console.log(body);
});
Thus, in order to make the API call work, you need to make the HTTP request valid (following to the document).

step by step implementation of nativescript push notification in nativescript

can anyone give step by step guidence starting from creating a helloworld app then the remaining steps to do push notifications.
i have already gone through the below link and failed to achieve that
https://github.com/EddyVerbruggen/nativescript-plugin-firebase
i have some progress on it, refer below code.
http.request({
url: 'https://fcm.googleapis.com/fcm/send',
method: "POST",
headers: { 'Authorization': 'key=AIzaSyBri16HAa7g2REEy******YFnTDGIlM_1k', 'Content-Type': 'application/json' },
content: JSON.stringify({
"notification": {
"title": "testingtesting",
"text": "some text",
"sound": "default",
"click_action": "GENERAL",
"badge": "1",
"showWhenInForeground": true
},
"content_available": false,
"data": {
"foo": "bar"
},
"priority": "High",
'to': "AAAACcS8hG0:APA91bEonX87xRfBHvccNheOR2ppFHZKaFlGGm6PRF6eEEYZg5Gd7uU_OU0GRJ0MkiTrR2gSDGO7Nz6BByujX4ex1jGgKpO20SXcGMa78k405vNV_4uJ1UDk_b-0-regi5x96KRcaOMH"
})
}).then((response) => {
//HttpResult = response.content.toJSON();
console.log('----------------------------------------------------');
console.log(response);
}, (e) => {
console.log("Error occurred " + JSON.stringify(e));
});
},
the response is as below.
JS: ----------------------------------------------------
JS: {
JS: "content": {
JS: "multicast_id": 5720873045813109000,
JS: "success": 1,
JS: "failure": 0,
JS: "canonical_ids": 0,
JS: "results": [
JS: {
JS: "message_id": "0:1548488437363910%0000000000000000"
JS: }
JS: ]
JS: },
JS: "statusCode": 200,
JS: "headers": {
JS: "null": "HTTP/1.1 200 OK",
JS: "Alt-Svc": "quic=\":443\"; ma=2592000; v=\"44,43,39\"",
JS: "Cache-Control": "private, max-age=0",
JS: "Content-Encoding": "gzip",
JS: "Content-Type": "application/json; charset=UTF-8",
JS: "Date": "Sat, 26 Jan 2019 07:40:37 GMT",
JS: "Expires": "Sat, 26 Jan 2019 07:40:37 GMT",
JS: "Server": "GSE",
JS: "Transfer-Encoding": "chunked",
JS: "X-Android-Received-Millis": "1548488436596",
JS: "X-Android-Response-Source": "NETWORK 200",
JS: "X-Android-Selected-Protocol": "http/1.1",
JS: "X-Android-Sent-Millis": "1548488436437",
JS: "X-Content-Type-Options": "nosniff",
JS: "X-Frame-Options": "SAMEORIGIN",
JS: "X-XSS-Protection": "1; mode=block"
JS: }
JS: }
even it says success. i have not got any notification on android. i'm not using ios.
I am fairly new here, but I realized you are much more likely to get a solution to your problem if you post your Nativescript code here, along with your questions. That way, we can look to see where your code is failing. Regarding this plugin, I will tell you it is imperative you follow every step in the readme file that comes with the plugin. I also had a heck of a time getting this to work, but now I have push notifications working.
Here is an example of NativeScript push notifications in action. This app will also teach you how they achieved their Push Notifications. These are the nicest Push Notifications I have run across yet. NativeScript Push Notification Examples
Please post your page XML and js code-behind, and we'll have a look. Also be sure this value is set properly, as this caused me a headache. Good luck, post your code so we can help!
Tip: Make sure your project number exactly matched your Firebase project value.
var pushSettings = {
senderID: "<ENTER_YOUR_PROJECT_NUMBER>", // Required: setting with the sender/project number
notificationCallbackAndroid: function (stringifiedData, fcmNotification) {
var notificationBody = fcmNotification && fcmNotification.getBody();
_this.updateMessage("Message received!\n" + notificationBody + "\n" + stringifiedData);
}
};

Resources