I have an if-else statement in a function. I want to test both cases. When the instance is initiated, self.count is set to 1. When I run my test, it goes to the false statement. How can I make self.count = 2 to go into the else statement?
Test:
it('verify change', function () {
spyOn(this.instance, 'change').and.callThrough();
this.instance.change('messageBoard');
expect(this.instance.change).toHaveBeenCalled();
});
Javascript:
self.count = 1;
self.change = function change() {
if(self.count <= 1) {
// do stuff
} else {
// do stuff
}
};
I know I can use this.object.method.and.returnValue() to make a method return a value, but I don't know how to do it with variables.
So it seems i do not need to mock the variables. I can just assign it within the test like:
it('verify change', function () {
this.instance.count = 2; // this would nake it go to the else block
spyOn(this.instance, 'change').and.callThrough();
this.instance.change('messageBoard');
expect(this.instance.change).toHaveBeenCalled();
});
Related
I'm trying to cancel a requestAnimationFrame loop, but I can't do it because each time requestAnimationFrame is called, a new timer ID is returned, but I only have access to the return value of the first call to requestAnimationFrame.
Specifically, my code is like this, which I don't think is entirely uncommon:
function animate(elem) {
var step = function (timestamp) {
//Do some stuff here.
if (progressedTime < totalTime) {
return requestAnimationFrame(step); //This return value seems useless.
}
};
return requestAnimationFrame(step);
}
//Elsewhere in the code, not in the global namespace.
var timerId = animate(elem);
//A second or two later, before the animation is over.
cancelAnimationFrame(timerId); //Doesn't work!
Because all subsequent calls to requestAnimationFrame are within the step function, I don't have access to the returned timer ID in the event that I want to call cancelAnimationFrame.
Looking at the way Mozilla (and apparently others do it), it looks like they declare a global variable in their code (myReq in the Mozilla code), and then assign the return value of each call to requestAnimationFrame to that variable so that it can be used any time for cancelAnimationFrame.
Is there any way to do this without declaring a global variable?
Thank you.
It doesn't need to be a global variable; it just needs to have scope such that both animate and cancel can access it. I.e. you can encapsulate it. For example, something like this:
var Animation = function(elem) {
var timerID;
var step = function() {
// ...
timerID = requestAnimationFrame(step);
};
return {
start: function() {
timerID = requestAnimationFrame(step);
}
cancel: function() {
cancelAnimationFrame(timerID);
}
};
})();
var animation = new Animation(elem);
animation.start();
animation.cancel();
timerID; // error, not global.
EDIT: You don't need to code it every time - that's why we are doing programming, after all, to abstract stuff that repeats so we don't need to do it ourselves. :)
var Animation = function(step) {
var timerID;
var innerStep = function(timestamp) {
step(timestamp);
timerID = requestAnimationFrame(innerStep);
};
return {
start: function() {
timerID = requestAnimationFrame(innerStep);
}
cancel: function() {
cancelAnimationFrame(timerID);
}
};
})();
var animation1 = new Animation(function(timestamp) {
// do something with elem1
});
var animation2 = new Animation(function(timestamp) {
// do something with elem2
});
I have a requirejs module created with the following pattern:
// foo.js
define(function(){
var x = 0;
function doStuff(){
return ++x;
}
return { doStuff: doStuff };
});
And a QUnit test which looks something like this:
// testfoo.js
define(['QUnit, foo'], function(QUnit, foo){
function setup(){
//...?
}
function teardown(){
//...?
}
function runTests(){
QUnit.test('foo counter remains at 1 on multiple tests', function(assert){
assert.equal(foo.doStuff(), 1); // this will work
});
QUnit.test('foo counter remains at 1 on multiple tests', function(assert){
assert.equal(foo.doStuff(), 1); // this obviously won't
});
}
return runTests;
});
How can I reset foo for each test?
I would like to keep foo a revealing module, i.e. not converting it to a constructor function with an altered prototype.
I tried var foo = require('foo');, but since requirejs is AMD based, it will complain about things getting loaded in the wrong order.
I suggest checking out SquireJS to create an isolated context for your tests. Squire is designed to inject mock dependencies by creating an isolated RequireJS context. A side effect of this is that the 'foo' library will be reload each time you call injector.require(), resetting the state of your library. The only downside is that your tests will need to be asynchronous.
// testfoo.js
define(['Squire', 'foo'], function (Squire, foo) {
'use strict';
QUnit.start();
QUnit.module('foo', {
setup: function () {
},
teardown: function () {
}
});
QUnit.test('Testing foo counter in main context.', 2, function (assert) {
assert.equal(foo.doStuff(), 1); // this will work
assert.equal(foo.doStuff(), 2); // this should work also.
});
QUnit.test('Testing foo counter in context created by Squire.', 1, function (assert) {
var done = assert.async(),
injector = new Squire();
injector.require([
'foo'
], function (foo) {
assert.equal(foo.doStuff(), 1); // this will work.
done();
});
});
});
I've posted a sample project here: qunit-squirejs
While this certainly isn't the cleanest way about it, by saving the function as a string, and recreating the function before each test, you can accomplish the same effect.
var fooString = foo.toString();
QUnit.testStart(function() { eval('foo = ' + fooString});
I'm trying to make a generic error message function that I can use within any JavaScript function. This function would test for certain validity and stop the calling function dead-cold if it fails.
For example:
var fun = function() {
var a = {};
a.blah = 'Hello';
checkIfExistErrorIfNot(a); // fine, continue on...
checkIfExistErrorIfNot(a.blah); // fine, continue on...
checkIfExistErrorIfNot(a.notDefined); // error. stop calling method ("fun") from continuing
console.log('Yeah! You made it here!');
}
This was my first stab at it:
var checkIfExistErrorIfNot(obj) {
var msg = 'Object does not exist.';
if(!obj) {
return (function() {
console.log(msg);
return false;
})();
}
return true;
}
The returning anonymous function executes just fine. But the calling function still continues. I'm guessing it's because the anon function does not execute in the scope of the calling function.
Thanks.
EDIT
I may not have made my intentions clear. Here is what I normally do in my methods:
saveData: function() {
var store = this.getStore();
var someObj = this.getOtherObject();
if(!store || !someObj) {
showError('There was an error');
return false; // now, 'saveData' will not continue
}
// continue on with save....
}
This is what I'd like to do:
saveData: function() {
var store = this.getStore();
var someObj = this.getOtherObject();
checkIfExistErrorIfNot(store);
checkIfExistErrorIfNot(someObj);
// continue on with save....
}
Now, what would be even cooler would be:
...
checkIfExistErrorIfNot( [store, someObj] );
...
And iterate through the array...cancelling on the first item that isn't defined. But I could add the array piece if I can find out how to get the first part to work.
Thanks
You can use exceptions for that:
var checkIfExistErrorIfNot = function (obj) {
var msg = 'Object does not exist.';
if(!obj) {
throw new Error(msg);
}
}
var fun = function() {
var a = {};
a.blah = 'Hello';
try {
console.log('a:');
checkIfExistErrorIfNot(a); // fine, continue on...
console.log('a.blah:');
checkIfExistErrorIfNot(a.blah); // fine, continue on...
console.log('a.notDefined:');
checkIfExistErrorIfNot(a.notDefined); // error. stop calling method ("fun") from continuing
} catch (e) {
return false;
}
console.log('Yeah! You made it here!');
return true;
}
console.log(fun());
I see different topics about the toggle function in jquery, but what is now really the best way to toggle between functions?
Is there maybe some way to do it so i don't have to garbage collect all my toggle scripts?
Some of the examples are:
var first=true;
function toggle() {
if(first) {
first= false;
// function 1
}
else {
first=true;
// function 2
}
}
And
var first=true;
function toggle() {
if(first) {
// function 1
}
else {
// function 2
}
first = !first;
}
And
var first=true;
function toggle() {
(first) ? function_1() : function_2();
first != first;
}
function function_1(){}
function function_2(){}
return an new function
var foo = (function(){
var condition
, body
body = function () {
if(condition){
//thing here
} else {
//other things here
}
}
return body
}())`
Best really depends on the criteria your application demands. This might not be the best way to this is certainly a cute way to do it:
function toggler(a, b) {
var current;
return function() {
current = current === a ? b : a;
current();
}
}
var myToggle = toggler(function_1, function_2);
myToggle(); // executes function_1
myToggle(); // executes function_2
myToggle(); // executes function_1
It's an old question but i'd like to contribute too..
Sometimes in large project i have allot of toggle scripts and use global variables to determine if it is toggled or not. So those variables needs to garbage collect for organizing variables, like if i maybe use the same variable name somehow or things like that
You could try something like this..: (using your first example)
function toggle() {
var self = arguments.callee;
if (self.first === true) {
self.first = false;
// function 1
}
else {
self.first = true;
// function 2
}
}
Without a global variable. I just added the property first to the function scope.
This way can be used the same property name for other toggle functions too.
Warning: arguments.callee is forbidden in 'strict mode'
Otherwise you may directly assign the first property to the function using directly the function name
function toggle() {
if (toggle.first === true) {
toggle.first = false;
// function 1
}
else {
toggle.first = true;
// function 2
}
}
Now I have a prototype like:
function A() {}
A.prototype.run = function () {
console.log('run 1');
};
Given that I cannot change anything where A is at (no control over the source). I would like to extend the method run. Not only log run 1, also log run 2. I tried several different approaches, it does not work.
A.prototype.run = function () {
this.run.call(this);
console.log('run 2');
}
Or
A.prototype.run = function () {
arguments.callee.call(this);
console.log('run 2');
}
Anyone having a solution for this? I would rather not to copy what's inside the method run. Thanks!
A.prototype._run = A.prototype.run;
A.prototype.run = function () {
this._run.call(this);
console.log('run 2');
}
You can override the run method, saving a reference to it as such;
(function (orig) {
A.prototype.run = function () {
orig.apply(this, arguments);
console.log('run 2');
}
}(A.prototype.run));
This is similar to your first attempt, but preserves the first value of run, so you can effectively do this.run.call(this) as you attempted.