I have multiple functions and a lot of code inside $(document).ready(function())
. I am using jasmine to test the functions inside the ready function as well as the code inside ready()
but when the test cases inside describe are executed it is not able to access the code inside the ready
function.
$(document).ready(function () {
function testMe(){
testVar = true;
}
});
Jasmine test suite
describe("test suite", function(){
beforeEach(function () {
testme = false
});
it("Test Alert Box Message For Change Modal", function() {
expect(testme).toEqual(true);
});
});
Kindly suggest what approach needs to be taken for the above approach.
2
in your code, domready calls an annonymous function. If we had a reference to this function, we could call it.
var onReady = function(){
testVar = true;
}
$(document).ready(onReady);
and in your tests
it("Test Alert Box Message For Change Modal", function() {
var testVar = false;
onReady() ;
expect(testVar).toEqual(true);
});
your code is now testable 🙂 namespacing and modules are recommended to make it even better.
What is inside the ready function is encapsulated in a separate scope from everything globally.
Put your test cases in the same scope to work.
There other approaches to be taken, is to do with closures, wrapping the anonymous function (in the ready event handler), putting it in a variable and then passing it to ready..
And then using that variable to pass to the test suites.
It can be complex to explain and implement to someone who doesnt know object oriented javascript..
var testMe;
$(document).ready(function () {
testMe=function testMe(){
testVar = true;
}
});
testMe is now defined. That created a closure.
I forgot the names of those techniques, I think i created hoisting..
anyway..an excellent book to read is Effective Javascript, to familiarize your self with good javascript techniques..It isnt like your usual programming language
4