If you’re testing your javascript with QUnit, you’ll probably run into the case where you need to initialize variables, objects, … before every test. You’ll want to run every test with the same baseline.
In NUnit, you can use the SetUp attribute for this. In QUnit, it’s a little different, but nothing too hard.With the module function, you can group tests and have them run a function before starting each test. The module requires at least a string containing the name of the group, but can accept an object containing a setup and teardown property, which are both functions:
var tv;
module("Television channel tests", {
setup: function () {
tv = new Television();
}
});
test("When moving the channel up", function() {
tv.channelUp();
equal(tv.getChannel(), 2, "The channel must be two.");
});
test("When moving the channel down", function() {
tv.channelDown();
equal(tv.getChannel(), 0, "The channel must be zero.");
});
module("Television brand tests", {
setup: function () {
tv = new Television("Sony");
}
});
test("When requesting the brand", function() {
tv.channelDown();
equal(tv.brand, "Sony", "The brand must be Sony.");
});
Just put the module before any tests you want to ‘contain’ in the module. Any tests after a new call to module will be seen as part of this new module. This is what you’ll see as a result:If your interested in all the code, you can check out my BitBucket repository.