Sinon stub.returns() not returning correct value - sinon

Sinon stub.returns() method does not return the correct response according the documentation. Any ideas why?
stubThis = sinon.stub().returns('123');
console.log(stubThis); // returns stub, but expect it to return 123

You need to invoke stubThis: console.log(stubThis());
When you call sinon.stub() you get back a function that returns undefined:
var stub = sinon.stub();
stub() // return undefined
When you invoke the .returns method on that function you specify its return value and get back the original function:
stub.returns('123') === stub; // true
stub() // now returns '123'
So in your code above stubThis is not supposed to be '123'. It is a function whose return value is '123'. You just need to invoke stubThis:
console.log(stubThis()); // logs '123'

Related

TypeScript Generics: Create a Generic Error Handler Function

I am having an error handler which gets two parameters, error which is of type unknown. It can be an object, a string, etc. and then return value which is of generic type. It can be an empty string, empty array or an empty object.
Here's how my function looks:
const genericErrorHandler = <T>(error: any, returnValue: T): T => {
console.log('Error = ', error);
return returnValue;
};
But I am not sure about calling this function. Here's how I expect it to behave:
genericErrorHandler({statusCode:404},"Not Found") should return "Not Found"
genericErrorHandler("Internal Server Error", {}) should return {}
genericErrorHandler({message:"Invalid TOken"},[]) should return []
with their respective logging. How do I call this function for above 3 cases and do I need to modify my actual function too?

Firebase Function Get Single Value From Database

I want to get a single value from Firebase Database within Firebase function. However, the Promise never returns and the chained method never executes. Here is the method that fetches a value from the database
function getFcmToken(username){
return admin.database().ref('tokens/{username}/fcmToken').once('value').then(snap => {
if(snap.exists()){
const token = Object.keys(snap.val());
console.log("FCM Token", token);
return token;
}
return [];
});
}
The above method was supposed to return a token, but I am not sure it is, so the method below does not get executed.
function sendNotification(keyword, username){
return getFcmToken(username).then(token => {
if(token.length > 0){
//Notification Detail
let payload = {
data:{
keyword: keyword
}
};
return admin.messaging().sendToDevice(token, payload);
}
});
}
In the console log, all I see is Promise pending.
How can I update the code above to return a single value, it appears it is returning an array?
Thanks
Your database ref path is wrong. You might wanted to replace username in path, but single quoted won't do that.
Firebase is listening on tokens/{username}/fcmToken, which doesn't exists. Hence on value event will not be triggered and so downline callback will not be executed.
You can use Template literals for building dynamic strings.
Try ref path as
`tokens/${username}/fcmToken`
Code:
function getFcmToken(username){
return admin.database().ref(`tokens/${username}/fcmToken`).once(...)
}

Return value from async call

I know this has been asked many times.I have a Javascript function that need return result from a async call.
function IsValid(callback){
$.ajax({
url:...
success:(function(data){
callback(data);
});
};
IsValid(function(data){
//process returned data
};
Also I can use promise to do similar job. However, what I need is IsValid function must return a bool value, not process the result directly.i.e, I need
if (IsValid())
//process
because IsValid function will be called in different function and the process is different on each caller function.
Any help will be appreciated. Thanks.
Use promises. jQuery returns a deferred object for AJAX calls, which acts like a Promise:
function IsValid() {
return $.ajax({
url:...
});
}
IsValid().then(function(data) {
// process returned data
});

isomorphic-fetch and redux-saga, how to call it properly ? how to manage it with generators?

It tells me "promise is not a function". My problem is that with isomorphic fetch you have to put twice then to get your parsed result. What should I do to manage that properly with redux-saga generators ?
import { put, call, takeEvery, takeLatest } from 'redux-saga/effects'
import fetch from 'isomorphic-fetch'
import errorMessages from './../conf/errorMessages'
function *fetchBalances(address) {
try {
var request = fetch('/api/getBalances/rJnZ4YHCUsHvQu7R6mZohevKJDHFzVD6Zr').then(function(response) {
return response.json();
}). then(function(result) {
// finally my parsed result !
return result;
});
const balances = yield call(request)
yield put({ type: 'GET_BALANCES_SUCCEED', balances: balances})
}
catch(error) {
yield put({ type: 'GET_BALANCES_ERROR', error: error })
}
}
export function* watchGetBalances() {
yield takeEvery('GET_BALANCES', fetchBalances);
}
I could put that in a closure but is that the best idea ? =/
var request = function() {
return fetch('/api/getBalances/rJnZ4YHCUsHvQu7R6mZohevKJDHFzVD6Zr').then(function(response) {
return response.json();
}). then(function(result) {
return result;
});
}
The confusion here comes from the fact that the request variable that you're passing to the call effect holds a Promise. What you want, is the call effect to execute that Promise for you.
In other words, you have already manually called the fetch function, instead of passing call a function that will call and return it.
So, yes, wrapping your fetch calls in a, eg. callRequest function could be useful but if you do so, you must be careful to write const response = yield call(callRequest), and not const response = yield call(callRequest()), which would be equivalent to what you wrote.
A few precisions, in case it helps. From the docs, call receives as its first argument:
A Generator function, or normal function which either returns a Promise as result, or any other value.
Let's see how that works.
First a generator function.
const response = yield call(myFunction);
function* myFunction() {
yield delay(1000);
return true;
}
// response === true
Then a function returning some value (not the most useful, but…)
const response = yield call(myFunction);
function myFunction() {
return true;
}
// response === true;
Finally a function returning a Promise
const response = yield call(callRequest);
function callRequest() {
return fetch(…).then( r => r.json() )
}
// response holds your data
// if the Promise were to be rejected, you could catch
// the error in a try-catch block

Promises in angular2 with firebase

Can someone explain how to correctly implement promise in Angular2 and Firebase.
I've read some articles such as this https://www.firebase.com/blog/2016-01-21-keeping-our-promises.html
in my app.component.ts file i have this
export class AppComponent{
players: Player[];
constructor(private _playerService: PlayerService){}
getPlayers(){
this._playerService.getPlayers().then(res => this.players = res);
}
ngOnInit(){
this.getPlayers();
}
}
inside the player.service.ts file I have this
getPlayers() {
this.playersRef.once('value', function (snap){
return snap.val();
});
}
I always get TypeError: this._playerService.getPlayers(...) is undefined
I also tried this as the article on top suggests
getPlayers() {
var data;
this.playersRef.once('value').then( function (snap){
data = snap.val();
});
return data;
}
But then i get this: Error: Query.once failed: Was called with 1 argument. Expects at least 2. in [null]
I'm not sure how the article is working at all with .once('value').then()
Problem occurs because you are trying to using .then over a method which isn't using promise. Basically missed to return promise from getPlayers method, you should return promise from there to perform promise chaining using .then method over it.
Also don't use callback to return value from it(because callback are not capable of returning anything from it), use .then function over .once so that you can extend promise chain & will be able to return out data correctly.
Code
getPlayers() {
//returned promise here
return this.playersRef.once('value').then((snap) => {
return snap.val();
});
}

Resources