Jasmin test if callback parameter is called - javascript

so i have a function which checks if a checksum is changed and if so it calls the callback which is provided by a parameter.
var watchFileChange = function watchFileChange(oldChecksum, callback){
// some code about checking checksum
if(oldChecksum != newChecksum){
callback()
}
}
exports.watchFileChange = watchFileChange;
my Jasmin specs looks like this.
var t = require('../server.js');
describe("watchFileChange", function() {
spyOn(t.watchFileChange, 'Callback');
var file_false = {
'foo.txt': 'd41dcccc8f00b204e9800998ecf8427e'
}
var file_true = {
'foo.txt': 'd41d8cd98f00b204e9800998ecf8427e'
}
function Callback() {
console.log("Callback Called")
}
it("Checksum is not right, it should call Callback function", function() {
watchFileChange(file_false, Callback);
expect(Callback).toHaveBeenCalled();
});
});
But it just doesn't work that way because Callback is not defined i get that. So my question is there a way to check if the by parameter provided callback is called?

You can create a fake object where you can define you callback function, and then pass it as the argument
var init = {
callback: function() {
console.log("Callback Called")
}
};
describe("watchFileChange", function() {
beforeEach(function() {
spyOn(init, 'callback');
});
//...
it("Checksum is not right, it should call Callback function", function() {
watchFileChange(file_false, init.callback);
expect(init.callback).toHaveBeenCalled();
});
});

Related

Callback not working - Javascript

I have a (asynchronous) function that gets the ID of a logged in user in Chrome. I'm trying to return the value of the ID with a callback but it keeps returning 'undefined'.
Before someone tries to mark this a duplicate, I used the code from here (and tried other places too): How to return value from an asynchronous callback function? But it didn't work:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
callback(userInfo.id);
});
}
getGaia(function(id){
return id;
});
var gaiaId = getGaia();
I get the following error:
'callback' is a not a function
What exactly am I doing wrong / what is the correct code?
That is because you are not providing a callback.
function doSomethingLater(callback) {
setTimeout(callback, 1000);
}
console.log('This is before the callback');
doSomethingLater(function() {
console.log('This is the callback')
});
So when you are calling var gaiaId = getGaia(); you are not passing in a callback function
[Edit] This is what your code would need to look like:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
// This will call the function that you pass in below
//and pass in userInfo.if as a parameter
callback(userInfo.id);
});
}
var gaiaId = getGaia(function (id) {
// id === userInfo.id from above
// Do something with the id that you pass in
});
You can think of functions like variables in JavaScript,
So you can assign a function to a variable like this:
var foo = function () { ... }
This means that you can pass this into functions like normal variables. When you pass the function in as a parameter, you are assigning the function to the name that you specify in the parameters:
var foo = function () { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
All I have done above is, instead of creating the variable foo I just created the function inline:
var foo = function () { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
// Becomes:
function hasCallback(callback) {
callback(); // Using the function that you passed in
}
hasCallback(function () { ... });

Pass a function as a parameter that may not exist yet in Javascript

Is it possible to pass a callback function that does not exist yet? My goal is to have a common function that will wait for another callback function to exist, when it does exist, it should execute it. This is what I have so far, but I can't figure out how to pass the function in that doesn't exist as a function yet.
function RunTemplateFunction(callback, userInfo) {
if ($.isFunction(callback)) {
callback(userInfo);
} else {
var myInterval = setInterval(function () {
if ($.isFunction(callback)) {
clearInterval(myInterval);
callback(userInfo);
}
}, 200);
}
}
I run the function like this:
RunTemplateFunction(MyFunctionToRun, GetUserInfo());
I get MyFunctionToRun is undefined for obvious reasons, I also tried the workaround of passing the function as a string and then convert the string to a function using eval(). But that throws the same error. I also thought of using the new function(), but that actually creates a new function.
Any help is appreciated. thank you.
If you call RunTemplateFunction by undefined there is no way we can see, is callback is defined or not, as we don't have reference to anything.
If you can modify the declaration to accept object as below, we can achieve what we want
function RunTemplateFunction(options, userInfo) {
if ($.isFunction(options.callback)) {
console.log('called1',userInfo);
options.callback(userInfo);
} else {
var myInterval = setInterval(function () {
if ($.isFunction(options.callback)) {
console.log('Called dynamically!!');
clearInterval(myInterval);
options.callback(userInfo);
}
}, 200);
}
}
var options = {}
RunTemplateFunction(options,{user:122});
options.callback = function(){
console.log("I'm called!!");
}
This will print
Called dynamically!!
I'm called!!
EDIT:
We can also call callback function in following way without setInterval, it will look different but options.callback variable is replaced by template.callMe function and its instantaneous also.
function TemplateRunner(userInfo){
this.callMe = function(cb){
this.templateFunction(cb);
}
this.templateFunction = function(callback){
callback(userInfo);
}
}
var template = new TemplateRunner({user:100})
template.callMe(function(user){
console.log('call me1',user);
});
template.callMe(function(user){
console.log('call me2',user);
})
This will print
call me1 {user: 100}
call me2 {user: 100}

call a callback in other callback js

I wondering if we can set a function containing a Callback function as parameter to another function who takes a callback too.
Example
function save(err, data, cb){};
function get(id, cb){};
get('12', save)?
Of course, a variable can be passed as argument of a function!
It may be clearer for you if you do:
// This also works with the notation `function save(...)`
var save = function(err, data, cb) {
alert('save' + err); // save12
},
get = function(id, cb) {
alert('get' + id); // get12
cb(id); // This call the "save" function
}
;
get('12', save);
Just be careful to not stack your callback too much or you will enter in the callback hell world!
Yes you can, check this example:
jsFiddle Example
jQuery(document).ready(function () {
function1({
param: "1",
callback: function () {
function2({
param : "2",
callback: function(){
alert("hello");
}
})
}
});
});
function function1(params){
alert(params.param);
params.callback();
}
function function2(params){
alert(params.param);
params.callback();
}
I hope it will be useful.

How to pass method parameter?

var rF = function(callback) {
alert("there2222");
//additional calls
$(document).trigger("lc", [callback]);
};
var pSl = function(callback) {
var func = pSR; // how to pass callback parameter in function
rF(func);
};
var pSR = function(callback, vars) {
alert(callback);
alert(vars);
};
$(document).on("lc", function(e, callback) {
alert("theaaa");
alert(callback, "ssss");
});
$('img').click(function() {
pSl("lol");
});
I guess you want to pass along callback to pSR. In that case you can use .bind:
var func = pSR.bind(null, callback);
or you put the call in another function:
rF(function() {
pSR(callback);
});
However, the choice of the parameter name is questionable, since you seem to pass a string (not a function).

Function as a parameter javascript syntax

I have a function like this :
module.exports.download = function (cb) {
// Some Code
cb();
}
Is it the same to do this :
module.exports.copyimagefromalbumnext = function (callback) {
module.exports.download(callback);
}
or
module.exports.copyimagefromalbumnext = function (callback) {
module.exports.download( function () { callback(); } );
}
In advance thanks.
Is callback the same as function () { callback(); }
No. The second function neither cares about this context, passed arguments, nor the return value of an invocation. You could do
function() { return callback.apply(this, arguments); }
but that's just superfluous. Use the first approach and pass callback itself.

Categories

Resources