In earlier blog posts I have explained the ways in which server side code can be unit tested using MSpec and Specflow. This post details how JavaScript code can be unit tested in a similar fashion, however this time utilising QUnit. A simple calculator class is used an example for this post.
Below is the JavaScript file that will be tested by a QUnit test. The file is named calculator.js and contains a single function that takes two numbers as arguments and returns the summation.
Finally, the file to be tested (calculator.js) and the test file (calculatorTest.js) are added. To run the tests simply open the file in a web browser. The below is displayed:
This has been a very brief tutorial in how to setup a simple QUnit test. In later posts I hope to go into more extensive detail, including how to utilise mocking within QUnit.
Below is the JavaScript file that will be tested by a QUnit test. The file is named calculator.js and contains a single function that takes two numbers as arguments and returns the summation.
The test is simple to write. The QUnit.test takes a name (displayed in the browser when the tests are run) before the assertion is made. In this case an assert.ok is used but there are many possible assertions that can be used which are listed here. (In a later post I will detail how assert.deepEqual can be used to test methods that return JSON).
Within the assertion, the expected equality is passed in before the success message that will be displayed. Finally, the html file to run the tests needs to be created. In the header the QUnit css is referenced. In the body dividers for qunit and qunit-fixture are written before adding in the reference to the QUnit JS file.
Finally, the file to be tested (calculator.js) and the test file (calculatorTest.js) are added. To run the tests simply open the file in a web browser. The below is displayed:
This has been a very brief tutorial in how to setup a simple QUnit test. In later posts I hope to go into more extensive detail, including how to utilise mocking within QUnit.
Next: Using Mockjax with QUnit
Comments
Post a Comment