How compare an array of objects using chai? - javascript

I am trying to create a test to verify that when I send a request to add a provider, that value is stored in the database.
The test is sending the request, the provider is created, but when I am trying to add the assertions to check the values in the database, I can't.
let providerBd = await functions.getProvider(addProviderRequest.senderID);
console.log(providerBd);
expect(providerBd.razonsocial).to.equal(testCase.provider.senderAdminName);
Code
First I am logging the object with the value obtained in the DB. But the test fails because the value that it gets is undefined and I am expected 'Proveedor Mocha' in razonsocial.
Output
Thanks in advance!

My error is in this line:
expect(providerBd.razonsocial).to.equal(testCase.provider.senderAdminName);
It should be:
expect(providerBd[0].razonsocial).to.equal(testCase.provider.senderAdminName);
Now works :)

Related

Call a specific array in a JSON API call

I'm trying to call the API but it doesn't return me anything.
I'm calling it like: res.on('data', d => { const RetrieveFromApi = JSON.parse(d).FLUX.quote.USD.price;.
The API is successfully called since I can see it in the API history, and data is defined as d.
Can you help me please?
from your screen provided in comment, you passed one property you don't access to it which is data
So just add property data before FLUX
JSON.parse(d).FLUX.quote.USD.price;
^data.FLUX.quote.USD.price;
From the image of the log the object seems incomplete at the end, did you try to use JSON.stringify(d) to see if there are any errors on the json object? or copy the response on https://jsonlint.com to check?
Because the error message points that the parse doesn't find a valid json object, maybe that is the whole point.
And the other tip is to try to store the value of JSON.parse in an variable before trying to access his values.

Query documents in firestore from an array of ID's

I was wondering how I can query documents from a firestore collection from an array of ID's? I only want the documents in the collection that are in the array of ID's. I looked at another answer and think my approach is correct, however, I am getting an error.
(node:15105) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'data' of undefined
> at /Users/username/SideProjects/projectname/functions/index.js:40:38
> at processTicksAndRejections (internal/process/task_queues.js:95:5)
The error happens because the function is not finding any documents in the collection from that array of ID's. However, I double-checked the database and know that there are documents in the collection with ID's from the array.
const admin = require('firebase-admin')
....
let feedItems = db.collection(feedItemsCollection)
feedItemsList = feedItems.where(admin.firestore.FieldPath.documentId(), 'in', ['HPOorsSnbHpTYwwXxfWw']).get().then(snapshot2 => {
console.log(admin.firestore.FieldPath.documentId())
console.log("In feed Items")
//console.log(feedItemIds)
console.log(snapshot2[0])
//error happens on this line because snapshot2[0] returns undefined
console.log(snapshot2[0].data())
})
Snapshot2[0] returns undefined which I'm assuming means that no data was returned. I think I'm not properly calling documentId(), but don't know the fix.
There "maybe" two problems with your code. Follow both points to make sure things are working
Data inside snapshot2 maybe empty
You'll first have to fix your code to test this theory. You're not accessing data from snapshot2 correctly. To do it right, one way is this:
// `snapshot2` will have a `docs` property that you can leverage
const snapshot2Data = snapshot2.docs.map((doc) => doc.data());
.documentId() may not be doing what it's supposed to (as you said)
To test this theory, check if snapshot2Data is empty. Run :
console.log(snapshot2Data); // what do you get ?
If no, it's not empty and you got data back, then you're all set. Nothing more to do
If yes, it is empty, then run :
console.log(admin.firestore.FieldPath.documentId()); // what do you get ?
Did you get back a string? If no, then we have another problem. You'll need to take a closer look at your firebase-admin setup, as well.

JavaScript console.log showing Object as Array?

I am using Firebase Auth to create users and logging the error so that I can display it to the user. This logging is currently in test and goes as follows:
console.log(error);
console.log(typeof(error))
In my console I get the following:
[Error: [auth/invalid-email] The email address is badly formatted.]
object
Usually when I get an object it is returned in some kind of {} format so I am confused why it is now in seemingly-array-like format? Could someone shed on light on how this works?
In Javascript, arrays are actually objects with some additional functionality. So typeof([]) will return object.
It looks like the api is returning an array of Error objects. If you wanted to display those errors to the user, you could loop through the returned array and print/concatenate each Error's message property.

Can not print data from API request

I am trying to learn working with API calls and responses and I needed a basic value that comes from api response but I wasn't able to get it work. So here is my problem;
(function worker() {
$.get('URL', function(data) {
$('#numbers').html(data); });
})();
I use this code and this works perfectly fine, and writes the API response to my HTML page. Also the API calls return the value in this format;
{
"success":"true",
"field1": {"number1":"number1_val","number2":"number2_val"},
"field2": {"number11":"number11_val","number22":"number22_val"}
}
Now, I tried to write the values from API response and I was successfull for writing the "success" value like this;
$('#success_val').html(data.success);
It printed true value to my HTML website in given #success_val field. However, when I tried to write the field1, or the first value of field1, I wasn't successful. I tried
$('#numbers').html(data.field1); => No success, empty page
$('nu#mbers').html(data.field1[0]); => No success, empty page
So, at this point, what I need to store & use is the "number11" value from field 2. I have read and searched for over an hour and found out that this api return is not a valid "array" return, instead it is called "field" (I might be wrong), but I couldn't find any info about how can I get the "number11" data from this api response.
$('#numbers').html(data.field1); => No success, empty page
Does data.field1 exist for sure? or spelling check.
you can get keys by Object.keys(data).
If exist data, it return ["success", "filed2", "field2"].
In the same way, you already know key, like number11,
data.field2.number11 or data["field2"]["number11"] return value.
If you don't know key, data["filed2"][Object.keys(data)[0]] return value
Thanks to https://stackoverflow.com/users/10366589/sh-k I have solved the problem in given way;
As I wasn't able to print output from field2 to HTML, I have checked keys at field2 with this code;
alert(Object.keys(data.field2));
and it returned
number11,number22
since I only needed number11 from that API response, I did the following;
var.storednumber = Object.keys(data.field2);
var.storednumber = storednumber[0];
$('#numbers').html(storednumber);
and I was able to get the number I wanted printed on the screen without any problem :)
There could be a better solution or fix for the issue I am having, but for now, this has solved. I guess the problem lies on the API response type as it doesn't return an array formatted data.

Trying to get a snapshot of a variable from firebase gives me an error

Problem
In a social media app I am making with react native and firebase, I am trying to grab the number of comments a post has using the snapshot function of a variable I have saved on my servers, then I am going to add one to this variable when a user adds a new comment. My code to do so is right here:
firebase.database().ref('posts').child(this.state.passKey).update({
comments: firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
})
When I actually run this code, I get an error saying:
Reference.child failed: First argument was an invalid path = "undefined".
Paths must be non-empty strings and can't contain ".","#","$","[", or "["
At first I thought this might be that the "this.state.passKey" wasn't actually passing the key, but putting in a key I copied from the server didn't fix the problem.
My Server
-
To get the comments of particular post you should do like this
let postId='someId'
postRef=`/posts/${postId}`
firebase.database().ref(postRef).once("value", dataSnapshot => {
comment=dataSnapshot.val().comments
});
It looks like you're expecting this bit of code to query the database:
firebase.database().ref('posts/'+this.state.passKey).child('comments').snapshot.val() + 1
Unfortunately, it doesn't work that way. There's no snapshot property on a database Reference object returned by child() or ref().
Instead, you'll need to query the database at that reference, then when you're called back with its value, you can apply it elsewhere.
var ref = firebase.database().ref('posts/'+this.state.passKey+'/comments')
ref.once('value', function(snapshot) {
// use the snapshot here
})

Categories

Resources