A couple of weeks ago, I wrote posted about JavaScript unit testing with the YUI Test framework. In it, I mentioned that I would have liked to be able to reload the page between running each test fixture, to be sure that tests did not interfere with each other. On Twitter, YUI Test creator Nicholas C. Zakas pinged me saying “it's better to use setUp() and tearDown() to reset the environment rather than reloading the page and losing your place.”
He’s of course right – the KISS principle applies. Revisiting my code, what I should have done to ensure total isolation between each test was to use setUp and tearDown to create the context that each request required – in my case, dynamically creating the <span> element that the InlineEditor should work against in the setUp and deleting it in the tearDown. Here’s an updated version of one of the fixtures which uses this approach:
1: var testCase0 = new YAHOO.tool.TestCase(
2: {
3: name: "When clicking editable span",
4:
5: setUp: function()
6: {
7: var span = $("<span id='span'>test</span>"); // create the span to edit
8: span.appendTo($('#container')); // append it to the test container
9: this.editor = new InlineEditor(span);
10:
11: YAHOO.util.UserAction.click(span[0]); // click to begin editing
12: },
13:
14: test_span_is_turned_into_input: function()
15: {
16: var input = $('#span'); // find the element in the document
17:
18: // element should now be replaced with an input element
19: YAHOO.util.Assert.isInstanceOf(HTMLInputElement, input[0]);
20: },
21:
22: test_input_has_same_text_as_span: function()
23: {
24: var input = $('#span');
25: YAHOO.util.Assert.areEqual('test', input.val());
26: },
27:
28: tearDown: function()
29: {
30: $('#container').empty(); // clear the container
31: delete this.editor;
32: }
33: });
I’ve updated all the tests in the sample to follow this pattern; download it here.
Stay tuned for more posts on JavaScript unit testing over christmas as I start investigating other frameworks and start comparing them :)