Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 625 lines (418 sloc) 21.394 kB
4909b88 @ianb Rearrange templates and general arrangement. Added a tutorial
authored
1 <!DOCTYPE html>
2 <html class="no-js">
3 <head>
4 <meta charset="utf-8">
5 <script src="doctest.js"></script>
6 <link rel="stylesheet" href="doctest.css">
7 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
8 <title>A doctest.js tutorial</title>
9 <meta name="description" content="An introduction to the Javascript testing framework, doctest.js">
10 <meta name="viewport" content="width=device-width">
11 <link rel="stylesheet" href=".resources/boilerplate/css/normalize.min.css">
12 <link rel="stylesheet" href=".resources/boilerplate/css/main.css">
13 <link rel="stylesheet" href=".resources/doc.css">
14 <script src=".resources/boilerplate/js/vendor/modernizr-2.6.1.min.js"></script>
15 <!-- EXTRA_HEAD --><!-- /EXTRA_HEAD -->
16 </head>
17 <body class="autodoctest">
18
19 <a href="http://github.com/ianb/doctestjs"><img
20 style="position: absolute; top: 0; right: 0; border: 0;"
21 src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"
22 alt="Fork me on GitHub" /></a>
23
24 <div class="header-container">
25 <header class="wrapper clearfix">
26 <h1 class="title">Doctest.js: <!-- TITLE -->A Tutorial <!-- /TITLE --></h1>
27
28 <!--
29 <nav>
30 <ul>
31 <li><a href="#">nav ul li a</a></li>
32 <li><a href="#">nav ul li a</a></li>
33 <li><a href="#">nav ul li a</a></li>
34 </ul>
35 </nav>
36 -->
37
38 </header>
39 </div>
40
41 <div class="main-container">
42 <div class="main wrapper clearfix">
43
44 <!-- BODY -->
45
46 <article>
47 <section id="introduction">
48 <header>
49 <h1>What's it like?</h1>
50 </header>
51
52 <p>
53
54 So you've decided to finally get religion when it comes to testing your Javascript code? Or, you feel like testing just isn't as easy as it could be, and want to find a better way to test your Javascript code? Or even: you've thought about or tried doing Test Driven Development but you've found it hard to get going? Let's do this...
55
56 </p>
57
58 <p>
59
60 Doctest.js is basically <em>example code</em> and then <em>expected output</em>. This is really what most tests look like, but instead of lots of <code>assertEqual(example, expected)</code> this example/expected combination is embedded into the structure of the test.
61
62 </p>
63
64 <aside>
65 <h3>Page Setup</h3>
66
67 <p>
68 See <a href="#html">Setting Up Your HTML</a> to see how to get your test running in the browser.
69 </p>
70 </aside>
71
72 <p>
73
74 I'm going to get right into how the test code looks, but to actually <em>use</em> doctest.js you have to setup an HTML file in a specific format. That is described later in the <a href="#html">HTML section</a>.
75
76 </p>
77
78 <p>
79
80 The structure looks like something you've probably seen before. We add one new function, <code>print()</code>, that works a lot like <code>console.log()</code>. Then we have a comment that shows what we expect to be output. A really simple example:
81
82 <pre class="commenttest">
83 function factorial(n) {
84 if (typeof n != "number") {
85 throw "You must give a number";
86 }
87 if (n <= 0) {
88 return 1;
89 }
90 return n * factorial(n-1);
91 }
92
93 print(factorial(4))
94 // => 25
95 </pre>
96
97 </p>
98
99 <p>
100
101 See what I did there? 25 is totally the wrong answer! Also see what happened, the test just ran and told us so! There's also a summary of all the tests; if you do nothing it shows up at the top of the page, but in the interest of introducing the summary, here it is:
102
103 </p>
104
105 <p id="doctest-output" style="border: 1px solid #999"></p>
106
107 <p>
108
109 You'll notice it shows a failure (or more than one &mdash; it's the summary for all the examples in this tutorial). It also has a link to each failure, so you can jump to the problematic section.
110
111 </p>
112
113 <aside>
114 <h3>Quoting</h3>
115
116 <p>
117 If you are writing your tests inline in the document, remember that you don't need to quote <code>></code> as <code>&amp;gt;</code>, that's only needed for <code>&lt;</code>
118 </p>
119 </aside>
120
121 <p>
122
123 Let's look at what we did there: <code>print(factorial(4))</code> and <code>// => 25</code> &mdash; the output is just a comment that starts with <code>=></code>.
124
125 </p>
126
127 </section>
128
129 <section id="errors">
130 <header>
131 <h3>Testing for error conditions</h3>
132 </header>
133
134 <p>
135
136 You can also test errors:
137
138 <pre class="commenttest">
139 print(factorial(null));
140 // => Error: You must give a number
141 </pre>
142
143 When an exception is thrown it will print out <code>Error: (error text)</code> which you can match against. This way you can test for error conditions just like you test how "correct" invocations work. Note that the <code>print()</code> isn't really necessary here, you could do this just as well:
144
145 <pre class="commenttest">
146 factorial(null);
147 // => Error: You must give a number
148 </pre>
149
150 </p>
151
152 </section>
153
154 <section id="print">
155 <header>
156 <h3><code>print()</code> and output matching</h3>
157 </header>
158
159 <p>
160
161 <code>print()</code> pretty-prints things. This is important, because you have to "expect" the same output that <code>print()</code> produces. You can give multiple arguments, like with <code>console.log</code>.
162
163 <pre class="commenttest">
164 print({someProperty: 123, something: {a: 1, b: 2}, "foo": 123.1032, "another-property": [1,2,3,4]});
165 /* =>
166 {
167 "another-property": [1, 2, 3, 4],
168 foo: 123.1032,
169 someProperty: 123,
170 something: {a: 1, b: 2}
171 }
172 */
173 </pre>
174
175 You might notice that the attributes are alphabetized and are quoted only when necessary. If it's a small object it stays on one line:
176
177 <pre class="commenttest">
178 print({someProperty: 123});
179 // => {someProperty: 123}
180 </pre>
181
182 </p>
183
184 <p>
185
186 But sometimes the output is unpredictable; or rather you can predict it will change. When that's the case you can basically put a wildcard in the expected output: <code>...</code> &mdash; that will match anything, including multiple lines. In addition you can use <code>?</code> to match one word-like-thing (a number, symbol, etc; not <code>&quot;</code> or whitespace or other symbols). You can use it like this:
187
188 <pre class="commenttest">
189 print({
190 date: new Date(),
191 timestamp: Date.now()
192 });
193
194 // => {date: ..., timestamp: ?}
195 </pre>
196
197 </p>
198
199 <p>
200
201 You might notice that it <em>passes</em>, but you still get to see the actual output. This is a great way to show information that you can review, without actually testing. For instance, you might be testing something that connects to a server, in that case you might want to do this:
202
203 <pre class="commenttest">
204 var server = {url: "http://localhost:8000"} // or some calculated value
205 print(server.url);
206 // => ...
207 </pre>
208
209 Now if everything seems breaky you can be 100% sure of what server you are connecting to.
210
211 </p>
212
213 <p>
214
215 If you have a variable that is dynamic but you still care about the value, you should do something like this:
216
217 <pre class="commenttest">
218 var date = Date.now();
219 print(date == date, date);
220 // => true ...
221 </pre>
222
223 Think of this pattern of <code>print(x == y)</code> as a kind of <code>assertEqual()</code> equivalent.
224
225 </p>
226
227 </section>
228
229 <section id="async">
230 <header>
231 <h3>Testing async code</h3>
232 </header>
233
234 <p>
235
236 This is all well and good, but lots of code in Javascript is <em>asynchronous</em>, meaning that you don't just call a function that returns a value. Doctest.js has an answer to that too: a great answer!
237
238 </p>
239
240 <p>
241
242 For our example we'll use <code>XMLHttpRequest</code>, a common source of asynchronosity. We'll test a request (just a loopback request, but if you are testing a foreign service you'd need <a href="http://enable-cors.org/">CORS access</a>). When we instantiate and setup the request we don't have anything really to test &mdash; we want to test what happens when the request <em>completes</em>.
243
244 </p>
245
246 <p>
247
248 To do this we'll use <code>wait()</code> &mdash; when this function is calls the test runner will wait at the point where it sees <code>// =></code>, for a certain amount of time or until a certain condition is met. Only then will it compare all the output that has happened to what was expected, and run the next chunk of test.
249
250 </p>
251
252 <p>
253
254 You can use this like: <code>wait(function () {return true when done})</code> or <code>wait(millisecondsToWait)</code>. We'll use the first form, which is almost always better, since it allows the test to continue more quickly. Tests also always time out eventually (by default the timeout is 5000 milliseconds, i.e., 5 seconds &mdash; by convention everything in Javascript is in milliseconds).
255
256 <pre class="commenttest">
257 var endpoint = location.href;
258 print(endpoint);
259 // => ...
260
261 var req = new XMLHttpRequest();
262 req.open("GET", endpoint);
263 req.onreadystatechange = function () {
264 if (req.readyState != 4) {
265 // hasn't actually finished
266 return;
267 }
268 print("Result:", req.status, req.getResponseHeader('content-type'));
269 };
270 req.send();
271
272 wait(function () {return req.readyState == 4;});
273
274 print("Current state:", req.readyState);
275
276 /* =>
277 Current state: 1
278 Result: 200 text/html
279 */
280 </pre>
281
282 I put in something tricky there to try to clarify what <code>wait()</code> really does. You'll notice there's a call to <code>wait()</code> that makes sure that <code>req.readyState == 4</code> (that's the code that means the request is finished). But right after when we do <code>print(req.readyState)</code> it shows a readyState of 1. That's because the <em>entire</em> block is printed (from the previous <code>// =></code> output up until the next one). But the test runner keeps collecting output and doesn't run the next section until that <code>wait()</code> clause returns true.
283
284 </p>
285
286 <p>
287
288 Another thing to note is that <code>wait()</code> needs to be called when that block of code is run &mdash; it can't be inside a function that isn't called. That said, if you write test helper functions (and you should!), it often works well to put those calls in the helper function. We'll see an example of that next...
289
290 </p>
291
292 </section>
293
294 <section id="spy">
295 <header>
296 <h3>The Spy</h3>
297 </header>
298
299 <p>
300
301 Note: the next example will use some jQuery, just for the heck of it, though there is no special support for jQuery or other frameworks in Doctest.
302
303 </p>
304
305 <p>
306
307 If you use these tools you might end up writing code like this quite a lot:
308
309 <pre class="commenttest">
310 // We've embedded a button just below this element
311 var button = $('#example-button');
312 // Just to highlight what we're working with:
313 button.css({border: '1px dotted #f00'});
314 button.click(function () {
315 print('Button clicked');
316 });
317
318 // Now we test that our event handler gets called when we do an artificial click of the button:
319 button.click();
320 // => Button clicked
321 </pre>
322
323 <button id="example-button" type="button">Example Button</button>
324
325 </p>
326
327 <p>
328
329 But maybe we are curious about the arguments passed to that handler &mdash; even though we ignored the arguments, there was one passed. And we might want to show what <code>this</code> is bound to; <code>this</code> is kind of like an invisible extra argument passed to every function invocation. We could make a fancier <code>print()</code> statement there. But instead, there's also a handy tool for tracking calls: <code>Spy</code>.
330
331 </p>
332
333 <p>
334
335 An example:
336
337 <pre class="commenttest">
338 var button = $('#example-button2');
339 button.css({border: '1px dotted #00f'});
340 button.click(Spy('button.click'));
341 button.click();
342
343 // => ...
344 </pre>
345
346 <button id="example-button2" type="button">Example Button 2</button>
347
348 </p>
349
350 <p>
351
352 That's a lot more information! Let's break it down:
353
354 <pre>
355 <b style="color: #00a">&lt;button id="example-button2" style="border: 1px solid rgb(0, 0, 255); " type="button">Example Button 2&lt;/button>.</b><span style="color: #0a0">button.click</span>({ ...
356 </pre>
357
358 There's two bits of information here. The first is the value (in <span style="color: #00a">blue</span>) of <code>this</code>, which is the <code>#example-button2</code> element. You'll notice it shows the HTML of the element. If you want Spy to ignore this you can use <code>Spy('button.click', {ignoreThis: true})</code>.
359
360 </p>
361
362 <p>
363
364 The second value (in <span style="color: #0a0">green</span>) is the name we gave the Spy when we created it. Note that Spy names are also identifiers, that is, <code>Spy('button.click') === Spy('button.click')</code>.
365
366 </p>
367
368 <p>
369
370 Next of course is all the arguments. There's a lot of arguments there. They are... interesting. You'll notice some references to <code>...recursive...</code> which is what you get when you have self-referencing data structures. But maybe you want to test just a little of that structure without testing all of it. You might do something like this:
371
372 <pre class="commenttest">
373 // Spy('button.click') fetches the same Spy we were using before, which still has all its call information
374 // .formatCall() shows the way the Spy was last called.
375 print(Spy('button.click').formatCall());
376
377 /* =>
378 &lt;button...&lt;/button>.button.click({
379 currentTarget: &lt;button...
380 ...
381 timeStamp: ?,
382 type: "click"
383 })
384 */
385
386 </pre>
387
388 So we've tested that the <code>type</code> is click, that it has a timeStamp (though not the value) and that the <code>currentTarget</code> is a button (presumably the button we bound it to). We still get to <em>see</em> all the other information, we just aren't <em>testing</em> it. This can be helpful in the future when you realize there's more you want to test &mdash; you can look at the test output and transcribe more into the test. Or when something fails later you might want to inspect that output to make sure everything is what you expect (and when you see something unexpected that's also a great time to expand your test).
389
390 </p>
391
392 <p>
393
394 Spies have a bunch of options, and act as a kind of mock object as well. You can pass in options as the second argument, like <code>Spy('name', {options...})</code>. Some highlights:
395
396
397 <dl>
398 <dt><code>applies</code></dt>
399 <dd>This is a function that the Spy "wraps". So if you do <code>Spy('click', {applies: function (event) {this.remove(); return false;}})</code> then you'll get the same output printed, but you'll also run <code>this.remove()</code>.</dd>
400
401 <dt><code>writes</code></dt>
402 <dd>If you set this to <code>false</code> then it won't automatically print out the calls. The values of the calls will still be recorded, and you can use <code>aSpy.formatCall()</code> to see them.</dd>
403
404 <dt><code>ignoreThis</code></dt>
405 <dd><p>Lots of code binds <code>this</code> without intending too. It's really easy in Javascript to do this. For instance, if you do <code>handlers[i]()</code> then <code>this</code> will be <code>handlers</code>. (Instead you might do <code>var handler = handlers[i]; handler()</code>)</p>
406
407 <p>Anyway, sometimes you don't care about <code>this</code>, and using <code>{ignoreThis: true}</code> lets you do that.
408 </p></dd>
409
410 <dt><code>returns</code></dt>
411 <dd>If you want the Spy to return a value when its called, give the value here. Normally it returns <code>undefined</code>.</dd>
412
413 <dt><code>throwError</code></dt>
414 <dd>This makes the Spy throw the given error anytime it is called.</dd>
415
416 <dt><code>wait</code></dt>
417 <dd>If you use <code>Spy('name', {wait: true})</code> then the test will wait until the Spy has been called. This is a pretty common pattern. It's basically the same as <code>Spy('name').wait()</code>.</dd>
418
419 </dl>
420
421 </p>
422
423 <p>
424
425 You can set values like <code>Spy.defaultOptions.writes = false</code> if you want to set one of these by default.
426
427 </p>
428
429 <p>
430
431 If you want to inspect how the Spy has been called, you can check a few attributes:
432
433 <dl>
434
435 <dt><code>.called</code></dt>
436 <dd>True once this Spy has been called.</dd>
437
438 <dt><code>.self</code> and <code>.selfList</code></dt>
439 <dd>This is the value of <code>this</code>, or <code>.selfList</code> contains a history for each call.</dd>
440
441 <dt><code>.args</code> and <code>.argList</code></dt>
442 <dd>The arguments the function was called with, or <code>.argList</code> is a history of arguments.</dd>
443
444 </dl>
445
446 </p>
447
448 </section>
449
450 <section id="console">
451 <header>
452 <h3>console.log</h3>
453 </header>
454
455 <p>
456
457 This isn't a feature you have to <em>do</em> anything about, it's just there for you, so I'm just going to point it out.
458
459 </p>
460
461 <p>
462
463 When you use <code>console.log</code> (or any of its friends, like <code>console.warn</code>) those messages will be captured (in addition to going to the log as normal), and the output will be shown in the specific test where they happened. A quick example:
464
465 <pre class="commenttest">
466 function enumProps(object) {
467 console.log('obj', object);
468 var result = {}
469 for (var attr in object) {
470 if (typeof object[attr] == "number" && attr.toUpperCase() == attr) {
471 result[object[attr]] = attr;
472 }
473 }
474 return result;
475 }
476
477 print(enumProps($('#example-button')[0]));
478
479 // => {...}
480
481 </pre>
482
483 You can think of it a little like <code>print()</code> goes to stdout, and <code>console.log()</code> goes to stderr.
484
485 </p>
486
487 </section>
488
489 <section id="abort">
490 <header>
491 <h3>Giving Up</h3>
492 </header>
493
494 <p>
495
496 Tests often require some feature or setup to be usable at all. When it's not setup right you'll just get a bunch of meaningless failures. For this reason there's a way to abort all your tests. If you call <code>Abort()</code> then no further tests will be run. If you want to connect to a server, for instance, you might check that the server is really there, and if not then just abort the rest of the tests. For example:
497
498 <pre>
499 $.ajax({
500 url: '/ping',
501 success: Spy('ping', {wait: true, ignoreThis: true}),
502 error: function () {
503 Abort("Server isn't up");
504 }
505 });
506
507 // => ping(...)
508 </pre>
509
510 </p>
511
512 </section>
513
514 <section id="html">
515 <header>
516 <h2>Setting Up Your HTML</h2>
517 </header>
518
519 <p>
520
521 I wanted to show you all the cool features of doctest first, but you can't actually use any of them unless you set up a test runner page. Luckily the page is pretty simple. Let's say you've put doctest.js into <code>doctest/</code>:
522
523 <pre>
524 &lt;DOCTYPE html>
525 &lt;html>
526 &lt;head>
527 &lt;meta charset="UTF-8">
528 &lt;title>My Test&lt;/title>
529 &lt;script src="doctest/doctest.js">&lt;/script>
530 &lt;link href="doctest/doctest.css" rel="stylesheet">
531 <b>&lt;script src="mylibrary.js">&lt;/script></b>
532 &lt;/head>
533 &lt;body class="autodoctest">
534
535 A test:
536
537 &lt;pre class="commenttest">
538 test goes here
539 &lt;/pre>
540
541 &lt;/body>&lt;/html>
542 </pre>
543
544 </p>
545
546 <p>
547
548 Mostly it's just boilerplate: you have to include <code>doctest.js</code> and <code>doctest.css</code> and of course any libraries or dependencies of the thing you are testing. You also must use <b><code>&lt;body class="autodoctest"></code></b> &mdash; that's what tells doctest.js you want to find and run tests right away.
549
550 </p>
551
552 <p>
553
554 Each test then is in a <code>&lt;pre class="commenttest"></code>. You might not want to actully write your tests <em>inside</em> the HTML, and instead put them in a separate Javascript file. To do that use:
555
556 <pre>
557 &lt;pre class="commenttest" href="./my_tests.js">&lt;/pre>
558 </pre>
559
560 This will load the test code from <code>./my_tests.js</code> and inline it into the element. This is how I personally write most of my tests, though when moving between a narrative and tests (as I am doing in this tutorial) it is nice to keep the tests together with the descriptions.
561
562 </p>
563
564 <p>
565
935c252 @ianb Rearrange templates and general arrangement. Added a tutorial
authored
566 Note that specifically when you use <code>href="URL.js"</code> you can include the comment <code><b>// == SECTION</b> Section header</code>, and the <code>&lt;pre</code> element will turn into multiple elements with headers.
567
568 </p>
569
570 <p>
571
4909b88 @ianb Rearrange templates and general arrangement. Added a tutorial
authored
572 A pass/fail summary is automatically added to the top of the page, though you can use <code>&lt;div id="doctest-output">&lt;/div></code> to position it someplace specific (as we did in this tutorial).
573
574 </p>
575
576 </section>
577
578 </article>
579
580 <!--
581 <aside>
582 <h3>aside</h3>
583
584 <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sodales urna non odio egestas tempor. Nunc vel vehicula ante. Etiam bibendum iaculis libero, eget molestie nisl pharetra in. In semper consequat est, eu porta velit mollis nec. Curabitur posuere enim eget turpis feugiat tempor. Etiam ullamcorper lorem dapibus velit suscipit ultrices.</p>
585
586 </aside>
587 -->
588
589 <!-- /BODY -->
590
591 </div> <!-- #main -->
592
593 </div> <!-- #main-container -->
594
595 <div class="footer-container">
596 <footer class="wrapper">
597 <h3>doctest.js is by <a href="http://ianbicking.org">Ian Bicking</a>.
598 It's on <a href="https://github.com/ianb/doctestjs">github</a>!</h3>
599 </footer>
600 </div>
601
602 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
603 <script>
604 window.jQuery || document.write('<script src=".resources/boilerplate/js/vendor/jquery-1.8.1.min.js"><\/script>')
605 </script>
606
607 <script src=".resources/boilerplate/js/main.js"></script>
608
609 <script type="text/javascript">
610
611 var _gaq = _gaq || [];
612 _gaq.push(['_setAccount', 'UA-34921728-1']);
613 _gaq.push(['_trackPageview']);
614
615 (function() {
616 var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
617 ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
618 var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
619 })();
620
621 </script>
622
623 </body>
624 </html>
Something went wrong with that request. Please try again.