JavaScript Quiz #3

Understanding JavaScript by example is useful for absorbing the different concepts of the language quickly. In this post, I will illustrate a quick JavaScript Quiz to understand how JavaScript (+) operator works. Assume that we have the following JavaScript code:

var object1 = {
    someVar: 2,
    someName: "object1",
    valueOf: function () {	
        return this.someVar;
    },
    toString: function () {	
        return this.someName;
    }
};

var result = "I equal " + object1;

alert(result); //What is the output of the alert?

What is the output of the alert?

Read the complete answer

JavaScript Quiz #2

Now, it is the time for the second JavaScript quiz.

Assume that we have the following JavaScript code:

var someVar = "1";
var someObject = {
	someVar: 2,
	someMethod: function () {
		var someVar = 3;
		var _this = this;
		
		setTimeout(function() {
			var result = _this.someVar + this.someVar;
			
			alert(result); //What is the value of result here?
			
			if (result > 20) {
				+result--;
			} else {
				+result++;
			}
			
			alert(result); //What is the value of result here?
			
		}, 10);		
	}
};

someObject.someMethod();

The question is what is the output in each alert and Why?
.
.
.
.
.
.
.
.
.
.
.
.
.
In order to understand how this JavaScript example will work, we should know the following:
1. How the JavaScript “this” keyword works.
2. How the JavaScript operators work.

I illustrated in details how the JavaScript “this” keyword works here, in summary, “this” evaluates to the object on which the method was invoked. This means that _this.someVar inside the setIimeout will be evaluated to 2.

It is important to understand how the + Arithmetic operator work, in the following line:

var result = _this.someVar + this.someVar;

The value of result in this line will be evaluated to: 2 + “1” = “21”. This is because the + Arithmetic JavaScript operator always favors String which means that if you have a numeric + String, the numeric operand will be converted to String and the result of the + Arithmetic operator will be a simple String concatenation.

Then coming to the next line:

result > 20

Here there is a comparison between both String and a numeric, unlike the + Arithmetic operator, the JavaScript Relational operators favor numeric, which means that result will be converted to integer so the comparison will be 21 > 20 which will be evaluated to true.

Finally in the following line:

+result--;

The + unary operator can be used to convert its operand to integer, however, it has no effect here as the evaluation of the expression the — post-increment operator is executed before it which will convert result to integer and decrement it by 1.

This is the explanation why the alerts will produce the following results in order:
1. 21
2. 20

This is all about this quiz. Stay tuned for the next one soon!

>>Edited in 01 April 2013.

JavaScript Quiz #1

Having quizzes from time to time is very important in order to refresh our information. This is why I decided to post JavaScript quizzes in order to have a better understanding of JavaScript.

Assume that we have the following JavaScript code:

var someVar = 1;
var someObject = {
	someVar: 2,
	someMethod: function () {
		var someVar = 3;
		
		alert(this.someVar); //What is the result ???
		
		setTimeout(function(){
			alert(this.someVar); //What is the result ???
		}, 10);		
	}
};

someObject.someMethod();

The question is what is the output in each alert and Why?
.
.
.
.
.
.
.
.
.
.
.
.
.
In order to understand how this JavaScript example will work, we should know how the JavaScript “this” keyword works. It is important to know that within a body of JavaScript method, “this” evaluates to the object on which the method was invoked.

This mean in the “this.someVar” expression of the first alert, “this” will be evaluated to someObject object on which someMethod method was invoked, which will result in 2 (the value set in line 3).

In the “this.someVar” expression of the second alert, “this” will be evaluated to Window global object because of the window.setTimeout, which will result in 1 (the value set in line 1).

This is all about this quiz. Stay tuned for the next one soon!

JavaScript Variable Scope confusion for Java Developers

Sometimes, the Java developers that are new to the JavaScript world have a confusion regarding the variable scoping in JavaScript. Let’s see an example that will illustrate this confusion, consider that we are having the following Simple JavaScript code:

<script>
var someVar = 0;

{
    var someVar = 100;
}

alert(someVar);
</script>

Some of the new JavaScript developers (from Java background) will expect that the result of the someVar will be 0, because the defined someVar variable inside the inline block will be ignored once the inline block ends.

In fact, the end result will be 100, This is because JavaScript does not have the concept of Java block scopes, JavaScript has only two scopes:
1. Global Scope.
2. Local Scope which is applied ONLY on the function(s) level (A single function or functions inside function) NOT on any other type of block(s) level (such as loops and inline blocks).

To be able to understand JavaScript local scope, Let’s introduce a new function to our original example:

{
    var someVar = 100;
    //someVar will be visible everyWhere ...
}

function someFunction() {
    var someVar = 10; 
	
    //someVar will be visible only here as 10 ...
}

alert(someVar);
someFunction();
alert(someVar);

The result will be:

100
100

someFunction defines a someVar variable and initializes it to 10, the someVar variable will be visible as long as we are in the someFunction‘s scope, when the someFunction ends, the someVar‘s function variable will not be available anymore, this is why the second alert will produce 100 which is the original value of someVar that is defined in the Global scope.

What the JavaScript Unit Testing book covers?


The JavaScript Unit Testing book is a comprehensive practical guide that illustrates in details how to efficiently perform and automate JavaScript testing for web applications using the most popular JavaScript unit testing frameworks.

The book starts by explaining the concept of JavaScript unit testing and by exploring the bits of an interactive Ajax web application. Throughout the book chapters, the JavaScript part of the web application is tested using popular JavaScript unit testing frameworks (Jasmine, YUITest, QUnit, and JsTestDriver). The book illustrates how to generate JavaScript test reports, how to automate running the tests in the build and the continuous integration environments, and how to make all of the mentioned JavaScript unit testing frameworks work together in order to test the web applications in the most efficient way.

After reading this book, you will learn everything you need to know in order to make efficient JavaScript tests for the web applications. You will learn how to generate test and code coverage reports, how to automate running the JavaScript tests, and the bits of the JavaScript testing by following the book practical hands-on detailed examples.

You can order the book from: http://www.amazon.com/dp/1782160620/.

Finally, I would like to thank all of the persons that worked with me in order to produce this book (Acquisition Editor, Commissioning Editors, Technical Editors, Copy Editors, Project Coordinator, Proofreaders, Graphics Designers, Production Coordinator) and certainly the technical reviewer of this book Allan Lykke Christensen.

The Easiest way to check empty Objects in JavaScript

It is a very common requirement that is needed by many JavaScript developers to check if an object is empty in JavaScript without having to write more than one line of code. In the old days, you usually had to make the following for … loop in a common function isEmpty in order to check if the object is empty:

function isEmpty(myObject) {
    for(var key in myObject) {
        if (myObject.hasOwnProperty(key)) {
            return false;
        }
    }

    return true;
}

Thanks to ECMAScript 5, you can now just use the Object.keys() function to check the object keys, so you can check if the myObject (for example) is empty as follows:

Object.keys(myObject).length == 0

I wish that this tip can be useful for you.

java.lang.RuntimeException: Oh Snap! No server defined!

You may face this problem when you try to run the JsTestDriver (JSTD) tests. The reason behind this error is that JsTestDriver is unable to find the configuration file that declares the server directive. In order to solve this error, you need to specify the configuration file path using the --config parameter in the test running command as follows:

java -jar JsTestDriver.jar --config jsTestDriver.conf --tests all

“Efficient JavaScript unit testing” video session in CONFESS 2012

This video provides a presentation about how to make efficient JavaScript unit testing. I presented it in the CON-FESS 2012 international conference which was held in Leogang, Austria. I wish it can be useful.

See the presentation with the slides on Parleys.com

See the presentation with the slides on Parleys.com

and I included below the presentation:

“Efficient JavaScript unit testing” presentation in CONFESS 2012

I just got back from the International technical conference CONFESS 2012 which was held in Leogang, Austria. The conference was very cool, the hotel and the city were fantastic, the quality of the sessions and the speakers were great.

Now, I got finally some free time to share with you my presentation about my efficient JavaScript unit testing. I hope it will be useful for you. Once I get the video session, I will definitely share it with you as well.

Have a nice time.

JsTestDriver integration with Hudson

Abstract

JsTestDriver is one of the most efficient JavaScript unit testing tools. Integrating JsTestDriver with continuous integration tools is a mandatory step for ensuring the web application quality. In this article, I will illustrate how this sort of integration can be done between JsTestDriver and Hudson.

Installing Hudson

To install Hudson on your machine, you need to download it from http://hudson-ci.org/.

Run the following command to start Hudson:

java -jar hudson-2.2.0.war

You can start launching Hudson by typing the following address in your browser:

http://localhost:8080/

You should now be redirected to the Hudson home page.

Creating Hudson Job

First of all, you need to create a new Job in Hudson. You can do this by clicking on “New Job” and entering the Job name and selecting “Build a free-style software project” as shown in the figure below:

Configuring JsTestDriver with Hudson

Click the “Configure” link of the project. In the configuration page, enter the project description. In order to run the job periodically, you need to configure the “Build Triggers”. Check the “Build periodically” option and enter the cron-like expression. To run the job every 5 mins past the hour (for example), enter the following expression 5 * * * * as shown below in the figure:

In order to execute the JsTestDriver test command, you need to configure the “Build” section. There are many ways to do so, you can either add “Execute Shell”, “Invoke Ant or Maven2 or Maven3”, or “Execute Windows Batch command”. The latter case can be used when you are working on Windows environment. For the case of this example, I use the “Execute Windows Batch command” option and specify the path of the batch file as shown in the screenshot below:

The batch file has the following content:

java -jar JsTestDriver-1.3.4.b.jar 
      --config jsTestDriver.conf 
      --tests all 
      --testOutput c:/outputFolder 
      --reset

For the matter of simplicity, I assume that the JsTestDriver server is already started and some browsers are already captured. This step is not included in this post, however, This step also can be automated if required.

Testing the integration of JsTestDriver with Hudson

In order to test the integration of JsTestDriver with Hudson, this can be done by manually or automatically (as indicated in the “Build periodically” option). To test the integration manually, click on the “Build Now” link as shown in the screenshot below:

Click the “console output” link to check the output of the results:

setting runnermode QUIET
Firefox: Reset
...
Total 3 tests (Passed: 3; Fails: 0; Errors: 0) (3.00 ms)
  Firefox 12.0 Windows: Run 3 tests (Passed: 3; Fails: 0; Errors 0) (3.00 ms)

Notices

You may face this error while trying to run a new Job:

hudson java.io.IOException: Cannot run program "sh"

In order to fix this error, check this post:
http://www.technicaladvices.com/2012/05/04/hudson-java-io-ioexception-cannot-run-program-sh-resolution/.

More Information about JsTestDriver

Efficient JavaScript unit testing

Generating Test Reports using JsTestDriver

Running Jasmine on the top of the JsTestDriver test runner