setup sinon with jsTestDriver by example
Apr 10, 2013 00:00 · 379 words · 2 minute read
What is sinon ?
it help us to write stand alone test cases in javascript. it help us to spy, stub or mock methods or objects.
How to get it ?
you can download the library from sinonjs.org.
How to set it up?
All you need to do is put the downloaded file in your project and reference to it.
What is JsTestDriver?
it is test framework that help you to run unit test.
How to get it ?
you can download the latest version from google code.
How to set it up ?
Put the jar file on your project. Create jsTestDriver.conf file in the config you should define a server that you like to run the test under it. you can use your localhost with the port 9876 if you wish to run on your PC.
in the next step you should reference your source code and test code relatively from your config file as below.
jsTestDriver.conf
server: http://localhost:9876
load:
- sinon.js
- test/*.js
How to run the JsTestDriver ?
open the command line and navigate to your project directory.
start the server by below command
start server
java -jar JsTestDriver.jar --port 9876
open your browser and capture the server url from below address
http://localhost:9876/
Remote Console Runner
finally run your tests in another command line window but same directory, by below command
java -jar JsTestDriver.jar --tests all
Example
sinon test case
SinonTest = TestCase('SinonTest');
SinonTest.prototype.setUp = function () {
this._sandbox = sinon.sandbox.create();
};
SinonTest.prototype.tearDown = function () {
this._sandbox.restore();
};
SinonTest.prototype.testRun = function () {
expectAsserts(1);
assertTrue(true);
};
TestCase
we can group set of tests under a test case name and only run them
setUp
it run before each test .
tearDown
it run after each test
testRun
it is the name of our test, it should always start with “test” keyword.
What does the test do ?
the short answer is, not doing too much !.
it create sandbox with sinon for our test in the setUp section, so we can test our scenario in a separate environment and restore it in tearDown.
expectAsserts(1)
would make sure that we will be assert one thing in our scenario i.e assertTrue()
.
Download
Feel free to download the full source code of this example from my github.