Você está na página 1de 17

1/14/2014

Testing in Node.js | Nettuts+

Testing in Node.js
Gabriel Manricks on Jan 3rd 2014 with 4 Comments

Tutorial Details
Language: Node.js Tools: Mocha and Chai Difficulty: Beginner Estimated Completion Time: 30 Minutes View post on Tuts+ BetaTuts+ Beta is an optimized, mobile-friendly and easy-to-read version of the Tuts+ network. A test driven development cycle simplifies the thought process of writing code, makes it easier, and quicker in the long run. But just writing tests is not enough by itself, knowing the kinds of tests to write and how to structure code to conform to this pattern is what it's all about. In this article we will take a look at building a small app in Node.js following a TDD pattern. Besides simple 'unit' tests, which we are all familiar with; We can also have Node.js's Async code running, which adds an extra dimension in that we don't always know the order in which functions will run or we may be trying to test something in a callback or checking to see how an async function is working. In this article we will be building a Node app which can search for files that match a given query. I know there are already things for this (ack ) but for the sake of demonstrating TDD I think it could be a well rounded project. The first step is obviously to write some tests, but even before that, we need to choose a testing framework. You can use vanilla Node, as there is an a s s e r tlibrary built-in, but it's not much in terms of a test runner, and is pretty much the bare essentials. Another option and probably my favorite for general use is Jasmine. It's pretty self-contained, you don't have any other dependencies to add to your scripts and the syntax is very clean and easy to read. The only reason I am not going to use this today, is because I think Jack Franklin did an excellent job covering this in his recent Tuts+ series here, and it's good to know your options so you can pick the best tool for your situation.
http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/ 1/17

1/14/2014

Testing in Node.js | Nettuts+

What Well Be Building


In this article we will be using the flexible 'Mocha' test runner along with the Chai assertion library. Unlike Jasmine which is more like an entire test suite in one package, Mocha only takes care of the overall structure but has nothing to do with the actual assertions. This allows you to keep a consistent look and feel when running your tests, but also allows you to run whichever assertion library best fits your situation. So for example, if you were going to use the vanilla 'assert' library, you could pair it with Mocha to add some structure to your tests. Chai is a fairly popular option, and is also all about options and modularity. Even without any plugins, just using the default API you have three different syntaxes you can use depending on if you would like to use a more classic TDD style or a more verbose BDD syntax. So now that we know what we are going to use, let's get into the installation.

The Setup
To get started, let's install Mocha globally by running: 1 n p mi n s t a l lgm o c h a

When that completes create a new folder for our project and run the following inside it: 1 n p mi n s t a l lc h a i

This will install a local copy of Chai for our project. Next, create a folder named t e s tinside our project's directory, as this is the default location Mocha will look for tests. That's pretty much it for setup, the next step is to talk about how to structure your apps when following a test driven development process.

Structuring Your App


It's important to know, when following a TDD approach, what needs to have tests and what does not. A rule of thumb is to not write tests for other peoples already tested code. What I mean by this is the following: let's say your code opens a file, you don't need to test the individual f sfunction, it's part of the languge and is supposedly already well tested. The same goes when using third-party libraries, you shouldn't structure functions which primarily call these types of functions. You don't really write tests for these and because of this you have gaps in the TDD cycle.
http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/ 2/17

1/14/2014

Testing in Node.js | Nettuts+

Now of course, with every programming style there are a lot of different opinions and people will have different views on how to TDD. But the approach I use is that you create individual components to use in your app, each of which solves a unique functional problem. These components are built using TDD ensuring that they work as expected and you won't break their API. Then you write your main script, which is essentially all glue code, and does not need to be tested / can't be tested, in certain situations. This also means that most of your components can be reused in the future as they do not really have much to do, directly, with the main script. Following what I just said, it's common practice to create a folder named 'l i b ' where you put all the individual components. So up to this point you should have Mocha and Chai installed, and then a project directory with two folders: 'l i b ' and 't e s t '.

Getting Started With TDD


Just in case you are new to TDD I thought it would be a good idea to quickly cover the process. The basic rule is that you can't write any code unless the test runner tells you to. Essentially, youre writing what your code is supposed to do before actually doing it. You have a really focused goal while coding and you never compromise your idea by getting side-tracked or thinking too far ahead. Besides that, since all of your code will have a test affiliated with it you can be certain you will never break your app in the future. A test, in reality, is just a declaration of what a function is expected to do when run, you then run your test runner, which will obviously fail (since you haven't written the code yet) and then you write the minimum amount of code needed to pass the failing test. It's important never to skip this step, because sometimes a test will pass even before you add any code, due to other code you have in the same class or function. When this happens, you either wrote more code then you were supposed to for a different test or this is just a bad test (usually not specific enough). Again according to our rule above, if the test passes right away you can't write any code, because it didn't tell you to. By continuously writing tests and then implementing the features you construct solid modules that you can rely on. Once youre finished implementing and testing your component, you can then go back and refactor the code to optimize it and clean it up but making sure the refactoring doesn't fail any of the tests you have in place and more importantly, doesn't add any features that are untested. Every testing library will have its own syntax, but they usually follow the same pattern of making assertions and then checking if they pass. Since we are using Mocha and Chai let's take a look at both their syntaxes starting with Chai.

Mocha & Chai


http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/ 3/17

1/14/2014

Testing in Node.js | Nettuts+

I will be using the 'Expect' BDD syntax, because as I mentioned Chai comes with a few options out of the box. The way this syntax works is you start by calling the expect function, passing it the object you want to make an assertion on, and then you chain it with a specific test. An example of what I mean could be as follows: 1 e x p e c t ( 4 + 5 ) . e q u a l ( 9 ) ;

That's the basic syntax, we are saying expect the addition of 4and 5to equal 9 . Now this isn't a great test because the 4and 5will be added by Node.js before the function is even called so we are essentially testing my math skills, but I hope you get the general idea. The other thing you should note, is this syntax is not very readable, in terms of the flow of a normal English sentence. Knowing this, Chai added the following chain getters which don't do anything but you can add them to make it more verbose and readable. The chain getters are as follows: to be been is that and have with at of same a an Using the above, we can rewrite our previous test to something like this: 1 e x p e c t ( 4 + 5 ) . t o . e q u a l ( 9 ) ;

I really like the feel of the entire library, which you can check out in their API. Simple things like negating the operation is as easy as writing . n o tbefore the test: 1 e x p e c t ( 4 + 5 ) . t o . n o t . e q u a l ( 1 0 ) ;

So even if you have never used the library before, it won't be hard to figure out what a test is trying to do. The last thing I would like to look over before we get into our first test is how we structure our code in Mocha

Mocha
Mocha is the test runner, so it doesn't really care too much about the actual tests, what it cares about is the tests structure, because that is how it knows what is failing and how to layout the results. The way you build it up, is you create multiple d e s c r i b eblocks which outline the different components of your library and then you add i t blocks to specify a specific test.
http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/ 4/17

1/14/2014

Testing in Node.js | Nettuts+

For a quick example, let's say we had a JSON class and that class had a function to parse JSON and we wanted to make sure the parse function can detect a badly formatted JSON string, we could structure this like so: 1 2 3 4 5 6 7 d e s c r i b e ( " J S O N " ,f u n c t i o n ( ){ d e s c r i b e ( " . p a r s e ( ) " ,f u n c t i o n ( ){ i t ( " s h o u l dd e t e c tm a l f o r m e dJ S O Ns t r i n g s " ,f u n c t i o n ( ) { / / T e s tG o e sH e r e } ) ; } ) ; } ) ;

It's not complicated, and it's about 80% personal preference, but if you keep this kind of format, the test results should come out in a very readable format. We are now ready to write our first library, let's begin with a simple synchronous module, to get ourselves better acquainted with the system. Our app will need to be able to accept command line options for setting things like how many levels of folders our app should search through and the query itself. To take care of all this, we will create a module which accepts the command's string and parses all the included options along with their values.

The Tag Module


This is a great example of a module you can reuse in all your command line apps, as this issue comes up a lot. This will be a simplified version of an actual package I have on npm called ClTags. So to get started, create a file named t a g s . j sinside of the lib folder, and then another file named t a g s S p e c . j sinside of the test folder. We need to pull in the Chai expect function, as that will be the assertion syntax we will be using and we need to pull in the actual tags file so we can test it. Altogether with some initial setup it should look something like this: 1 2 3 4 5 6 v a re x p e c t=r e q u i r e ( " c h a i " ) . e x p e c t ; v a rt a g s=r e q u i r e ( " . . / l i b / t a g s . j s " ) ; d e s c r i b e ( " T a g s " ,f u n c t i o n ( ) { } ) ;

If you run the 'mocha' command now from the root of our project, everything should be passing like expected. Now let's think about what our module will do; we want to pass it the command arguments array that was used to run the app, and then we want it to build an object with all the tags, and it would be nice if we could also pass it a default object of settings, so if nothing get's overridden, we will have some settings already stored. When dealing with tags, a lot of apps also provide shortcut options which are just one character, so let's say we wanted to set the depth of our search we could allow the user to either specify something like d e p t h = 2or something like d = 2which should have the same effect. So let's just begin with the long formed tags (for example, 'depth=2'), To begin with, let's write the first test:
http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/ 5/17

1/14/2014

Testing in Node.js | Nettuts+

1 2 3 4 5 6 7 8 9 1 0 1 1

d e s c r i b e ( " T a g s " ,f u n c t i o n ( ) { d e s c r i b e ( " # p a r s e ( ) " ,f u n c t i o n ( ) { i t ( " s h o u l dp a r s el o n gf o r m e dt a g s " ,f u n c t i o n ( ) { v a ra r g s=[ " d e p t h = 4 " ," h e l l o = w o r l d " ] ; v a rr e s u l t s=t a g s . p a r s e ( a r g s ) ; e x p e c t ( r e s u l t s ) . t o . h a v e . a . p r o p e r t y ( " d e p t h " ,4 ) ; e x p e c t ( r e s u l t s ) . t o . h a v e . a . p r o p e r t y ( " h e l l o " ," w o r l d " ) ;

} ) ; } ) ;

} ) ;

We added one method to our test suite called p a r s eand we added a test for long formed tags. Inside this test I created an example command and added two assertions for the two properties it should pickup. Running Mocha now, you should get one error, namely that t a g sdoesn't have a p a r s efunction. So to fix this error let's add a p a r s efunction to the tags module. A fairly typical way to create a node module is like so: 1 2 3 4 5 e x p o r t s=m o d u l e . e x p o r t s={ } ; e x p o r t s . p a r s e=f u n c t i o n ( ){ }

The error said we needed a p a r s emethod so we created it, we didn't add any other code inside because it didn't yet tell us to. By sticking with the bare minimum you are assured that you won't write more then you are supposed to and end up with untested code. Now let's run Mocha again, this time we should be getting an error telling us that it can't read a property named d e p t hfrom an undefined variable. That is because currently our p a r s efunction isn't returning anything, so let's add some code so that it will return an object: 1 2 3 4 5 e x p o r t s . p a r s e=f u n c t i o n ( ){ v a ro p t i o n s={ } r e t u r no p t i o n s ; }

We are slowly moving along, if you run Mocha again, their shouldn't be any exceptions being thrown, just a clean error message saying that our empty object has no property called d e p t h .

Now we can get into some real code. For our function to parse the tag and add it to our object we need to cycle through the arguments array and remove the double dashes at the start of the key. 1 2 3 4 5 e x p o r t s . p a r s e=f u n c t i o n ( a r g s ){ v a ro p t i o n s={ } f o r( v a rii na r g s ){/ / C y c l et h r o u g ha r g s v a ra r g=a r g s [ i ] ; / / C h e c ki fL o n gf o r m e dt a g
6/17

http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/

1/14/2014

Testing in Node.js | Nettuts+

6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7

} r e t u r no p t i o n s ;

i f( a r g . s u b s t r ( 0 ,2 )= = =" " ){ a r g=a r g . s u b s t r ( 2 ) ; / / C h e c kf o re q u a l ss i g n i f( a r g . i n d e x O f ( " = " )! = =1 ){ a r g=a r g . s p l i t ( " = " ) ; v a rk e y=a r g . s h i f t ( ) ; o p t i o n s [ k e y ]=a r g . j o i n ( " = " ) ; } }

This code cycles through the list of arguments, makes sure we are dealing with a long formed tag, and then splits it by the first equals character to create the key and value pair for the options object. Now this almost solves our issue, but if we run Mocha again, you will see that we now have a key for depth, but it's set to a string instead of a number. Numbers are a bit easier to work with later on in our app, so the next piece of code we need to add is to convert values to numbers whenever possible. This can be achieved with some RegEx and the p a r s e I n tfunction as follows: 1 2 3 4 5 6 7 8 9 1 0 i f( a r g . i n d e x O f ( " = " )! = =1 ){ a r g=a r g . s p l i t ( " = " ) ; v a rk e y=a r g . s h i f t ( ) ; v a rv a l u e=a r g . j o i n ( " = " ) ; i f( / ^ [ 0 9 ] + $ / . t e s t ( v a l u e ) ){ v a l u e=p a r s e I n t ( v a l u e ,1 0 ) ; } o p t i o n s [ k e y ]=v a l u e ;

Running Mocha now, you should get a pass with one test. The number conversion should arguably be in its own test, or at least mentioned in the tests declaration so you don't, by mistake, remove the number conversion assertion; so just add-on add and convert numbers to the i tdeclaration for this test or separate it into a new i tblock. It really depends whether you consider this obvious default behavior or a separate feature.

Now like I have been trying to stress throughout this whole article, when you see a passing spec, it's time to write more tests. The next thing I wanted to add was the default array, so inside the t a g s S p e cfile let's add the following i tblock right after the previous one: 1 2 3 4 5 6 7 8 i t ( " s h o u l dp a r s el o n gf o r m e dt a g sa n dc o n v e r tn u m b e r s " ,f u n c t i o n ( ) { v a ra r g s=[ " d e p t h = 4 " ," h e l l o = w o r l d " ] ; v a rr e s u l t s=t a g s . p a r s e ( a r g s ) ; e x p e c t ( r e s u l t s ) . t o . h a v e . a . p r o p e r t y ( " d e p t h " ,4 ) ; e x p e c t ( r e s u l t s ) . t o . h a v e . a . p r o p e r t y ( " h e l l o " ," w o r l d " ) ;

} ) ; i t ( " s h o u l df a l l b a c kt od e f a u l t s " ,f u n c t i o n ( ) {

http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/

7/17

1/14/2014

Testing in Node.js | Nettuts+

9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0

v a ra r g s=[ " d e p t h = 4 " ," h e l l o = w o r l d " ] ; v a rd e f a u l t s={d e p t h :2 ,f o o :" b a r "} ; v a rr e s u l t s=t a g s . p a r s e ( a r g s ,d e f a u l t s ) ; v a re x p e c t e d={ d e p t h :4 , f o o :" b a r " , h e l l o :" w o r l d " } ; } ) ; e x p e c t ( r e s u l t s ) . t o . d e e p . e q u a l ( e x p e c t e d ) ;

Here we are using a new test, the deep equal which is good for matching two objects for equal values. Alternatively, you can use the e q ltest which is a shortcut but I think this is more clear. This test passes two arguments as the command string and passes two defaults with one overlap, just so we can get a good spread on the test cases. Running Mocha now, you should get a sort of diff, containing the differences between what is expected and what it actually got.

Let's now continue back to the t a g s . j smodule, and let's add this functionality in. It's a fairly simple fix to add, we just need to accept the second parameter, and when it's set to an object we can replace the standard empty object at the start with this object: 1 2 3 4 5 e x p o r t s . p a r s e=f u n c t i o n ( a r g s ,d e f a u l t s ){ v a ro p t i o n s={ } ; i f( t y p e o fd e f a u l t s= = =" o b j e c t "& &! ( d e f a u l t si n s t a n c e o fA r r a y ) ){ o p t i o n s=d e f a u l t s }

This will bring us back to a green state. The next thing I want to add is the ability to just specify a tag without a value and let it work like a boolean. For example, if we just set s e a r c h C o n t e n t sor something like that, it will just add that to our options array with a value of t r u e .

http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/

8/17

1/14/2014

Testing in Node.js | Nettuts+

The test for this would look something like the following: 1 2 3 4 5 6 i t ( " s h o u l da c c e p tt a g sw i t h o u tv a l u e sa sab o o l " ,f u n c t i o n ( ) { v a ra r g s=[ " s e a r c h C o n t e n t s " ] ; v a rr e s u l t s=t a g s . p a r s e ( a r g s ) ; } ) ; e x p e c t ( r e s u l t s ) . t o . h a v e . a . p r o p e r t y ( " s e a r c h C o n t e n t s " ,t r u e ) ;

Running this will give us the following error just like before:

Inside of the f o rloop, when we got a match for a long formed tag, we checked if it contained an equals sign; we can quickly write the code for this test by adding an e l s eclause to that i fstatement and just setting the value to t r u e : 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 i f( a r g . i n d e x O f ( " = " )! = =1 ){ a r g=a r g . s p l i t ( " = " ) ; v a rk e y=a r g . s h i f t ( ) ; v a rv a l u e=a r g . j o i n ( " = " ) ; i f( / ^ [ 0 9 ] + $ / . t e s t ( v a l u e ) ){ v a l u e=p a r s e I n t ( v a l u e ,1 0 ) ; } o p t i o n s [ k e y ]=v a l u e ; }e l s e{ o p t i o n s [ a r g ]=t r u e ; }

The next thing I want to add is the substitutions for the short-hand tags. This will be the third parameter to the p a r s efunction and will basically be an object with letters and their corresponding replacements. Here is the spec for this addition: 1 2 i t ( " s h o u l da c c e p ts h o r tf o r m e dt a g s " ,f u n c t i o n ( ) { v a ra r g s=[ " s d = 4 " ," h " ] ;
9/17

http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/

1/14/2014

Testing in Node.js | Nettuts+

3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8

v a rr e p l a c e m e n t s={ s :" s e a r c h C o n t e n t s " , d :" d e p t h " , h :" h e l l o " } ; v a rr e s u l t s=t a g s . p a r s e ( a r g s ,{ } ,r e p l a c e m e n t s ) ; v a re x p e c t e d={ s e a r c h C o n t e n t s :t r u e , d e p t h :4 , h e l l o :t r u e } ; } ) ; e x p e c t ( r e s u l t s ) . t o . d e e p . e q u a l ( e x p e c t e d ) ;

The trouble with shorthand tags is that they are able to be combined in a row. What I mean by this is unlike the long formed tags where each one is separate, with short hand tags since they are each just a letter long you can call three different ones by typing v g h . This makes the parsing a bit more difficult because we still need to allow for the equals operator for you to add a value to the last tag mentioned, while at the same time you need to still register the other tags. But not to worry, it's nothing that can't be solved with enough popping and shifting. Here is the entire fix, from the beginning of the p a r s efunction: 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 e x p o r t s . p a r s e=f u n c t i o n ( a r g s ,d e f a u l t s ,r e p l a c e m e n t s ){ v a ro p t i o n s={ } ; i f( t y p e o fd e f a u l t s= = =" o b j e c t "& &! ( d e f a u l t si n s t a n c e o fA r r a y ) ){ o p t i o n s=d e f a u l t s }

i f( t y p e o fr e p l a c e m e n t s= = =" o b j e c t "& &! ( d e f a u l t si n s t a n c e o fA r r a y ) ){ f o r( v a rii na r g s ){ v a ra r g=a r g s [ i ] ; i f( a r g . c h a r A t ( 0 )= = =" "& &a r g . c h a r A t ( 1 )! =" " ){ a r g=a r g . s u b s t r ( 1 ) ; i f( a r g . i n d e x O f ( " = " )! = =1 ){ a r g=a r g . s p l i t ( " = " ) ; v a rk e y s=a r g . s h i f t ( ) ; v a rv a l u e=a r g . j o i n ( " = " ) ; a r g=k e y s . s p l i t ( " " ) ; v a rk e y=a r g . p o p ( ) ; i f( r e p l a c e m e n t s . h a s O w n P r o p e r t y ( k e y ) ){ k e y=r e p l a c e m e n t s [ k e y ] ; } a r g s . p u s h ( " "+k e y+" = "+v a l u e ) ; }e l s e{ a r g=a r g . s p l i t ( " " ) ; }
10/17

http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/

1/14/2014

Testing in Node.js | Nettuts+

2 8 2 9 3 0 3 1 3 2 3 3 3 4 3 5 3 6

a r g . f o r E a c h ( f u n c t i o n ( k e y ) { i f( r e p l a c e m e n t s . h a s O w n P r o p e r t y ( k e y ) ){ k e y=r e p l a c e m e n t s [ k e y ] ; } a r g s . p u s h ( " "+k e y ) ; } ) ;

It's a lot of code (in comparison) but all we are really doing is splitting the argument by an equals sign, then splitting that key into the individual letters. So for example if we passed g j = a s dwe would split the a s dinto a variable called v a l u e , and then we would split the g jsection into individual characters. The last character (jin our example) will become the key for the value (a s d ) whereas any other letters before it, will just be added as regular boolean tags. I didn't want to just process these tags now, just in case we changed the implementation later. So what we are doing is just converting these short hand tags into the long formed version and then letting our script handle it later. Running Mocha again will take us back to our illustrious green results of four tests passing for this module. Now there are a few more things we can add to this tags module to make it closer to the npm package, like the ability to also store plain text arguments for things like commands or the ability to collect all the text at the end, for a query property. But this article is already getting long and I would like to move on to implementing the search functionality.

The Search Module


We just went through creating a module step by step following a TDD approach and I hope you got the idea and feeling of how to write like this. But for the sake of keeping this article moving, for the rest of the article, I will speed up the testing process by grouping things together and just showing you the final versions of tests. It's more of a guide to different situations which may come up and how to write tests for them. So just create a file named s e a r c h . j sinside the lib folder and a s e a r c h S p e c . j sfile inside of the test folder. Next open the spec file and let's setup our first test which can be for the function to get a list of files based on a d e p t hparameter, this is also a great example for tests which require a bit of external setup for them to work. When dealing with outside object-like-data or in our case files, you will want to have a predefined setup which you know will work with your tests, but you also don't want to add fake info to your system. There are basically two options to solve this problem, you can either mock the data, like I mentioned above if you are dealing with the languages own commands for loading data, you don't necessarily need to test them. In cases like that, you can simply provide the 'retrieved' data and continue on with your testing, kind of like what we did with the command string in the tags library. But in this case, we are testing the recursive functionality we are adding to the languages file reading capabilities, depending on the specified depth. In cases like these, you do need to write a test and so we need to create some demo files to test the file reading. The alternative is to maybe
http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/ 11/17

1/14/2014

Testing in Node.js | Nettuts+

stub the f sfunctions to just run but not do anything, and then we can count how many times our fake function ran or something like that (check out spies) but for our example, I am just going to create some files. Mocha provides functions which can run both before and after your tests, so you can perform these kinds of external setup and cleanup around your tests. For our example, we will create a couple of test files and folders at two different depths so we can test out that functionality: 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 v a re x p e c t=r e q u i r e ( " c h a i " ) . e x p e c t ; v a rs e a r c h=r e q u i r e ( " . . / l i b / s e a r c h . j s " ) ; v a rf s=r e q u i r e ( " f s " ) ; d e s c r i b e ( " S e a r c h " ,f u n c t i o n ( ) { d e s c r i b e ( " # s c a n ( ) " ,f u n c t i o n ( ) { b e f o r e ( f u n c t i o n ( ){ i f( ! f s . e x i s t s S y n c ( " . t e s t _ f i l e s " ) ){ f s . m k d i r S y n c ( " . t e s t _ f i l e s " ) ; f s . w r i t e F i l e S y n c ( " . t e s t _ f i l e s / a " ," " ) ; f s . w r i t e F i l e S y n c ( " . t e s t _ f i l e s / b " ," " ) ; f s . m k d i r S y n c ( " . t e s t _ f i l e s / d i r " ) ; f s . w r i t e F i l e S y n c ( " . t e s t _ f i l e s / d i r / c " ," " ) ; f s . m k d i r S y n c ( " . t e s t _ f i l e s / d i r 2 " ) ; f s . w r i t e F i l e S y n c ( " . t e s t _ f i l e s / d i r 2 / d " ," " ) ; } } ) ; a f t e r ( f u n c t i o n ( ){ f s . u n l i n k S y n c ( " . t e s t _ f i l e s / d i r / c " ) ; f s . r m d i r S y n c ( " . t e s t _ f i l e s / d i r " ) ; f s . u n l i n k S y n c ( " . t e s t _ f i l e s / d i r 2 / d " ) ; f s . r m d i r S y n c ( " . t e s t _ f i l e s / d i r 2 " ) ; f s . u n l i n k S y n c ( " . t e s t _ f i l e s / a " ) ; f s . u n l i n k S y n c ( " . t e s t _ f i l e s / b " ) ; f s . r m d i r S y n c ( " . t e s t _ f i l e s " ) ; } ) ;

} ) ; } ) ;

These will be called based on the d e s c r i b eblock they are in, and you can even run code before and after each i tblock using b e f o r e E a c hor a f t e r E a c hinstead. The functions themselves just use standard node commands to create and remove the files respectively. Next we need to write the actual test. This should go right next to the a f t e rfunction, still inside the d e s c r i b eblock: 1 2 3 4 5 6 7 8 i t ( " s h o u l dr e t r i e v et h ef i l e sf r o mad i r e c t o r y " ,f u n c t i o n ( d o n e ){ s e a r c h . s c a n ( " . t e s t _ f i l e s " ,0 ,f u n c t i o n ( e r r ,f l i s t ) { e x p e c t ( f l i s t ) . t o . d e e p . e q u a l ( [ " . t e s t _ f i l e s / a " , " . t e s t _ f i l e s / b " , " . t e s t _ f i l e s / d i r / c " , " . t e s t _ f i l e s / d i r 2 / d " ] ) ;
12/17

http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/

1/14/2014

Testing in Node.js | Nettuts+

9 1 0 1 1

} ) ;

} ) ;

d o n e ( ) ;

This is our first example of testing an async function, but as you can see it's just as simple as before; all we need to do is use the d o n efunction Mocha provides in the i tdeclarations to tell it when we are finished with this test. Mocha will automatically detect if you specified the d o n evariable in the callback and it will wait for it to be called allowing you to test asynchronous code really easily. Also, it's worth mentioning that this pattern is available throughout Mocha, you can for example, use this in the b e f o r eor a f t e rfunctions if you needed to setup something asynchronously. Next I would like to write a test that makes sure the depth parameter works if set: 1 2 3 4 5 6 7 8 9 i t ( " s h o u l ds t o pa tas p e c i f i e dd e p t h " ,f u n c t i o n ( d o n e ){ s e a r c h . s c a n ( " . t e s t _ f i l e s " ,1 ,f u n c t i o n ( e r r ,f l i s t ){ e x p e c t ( f l i s t ) . t o . d e e p . e q u a l ( [ " . t e s t _ f i l e s / a " , " . t e s t _ f i l e s / b " , ] ) ; d o n e ( ) ; } ) ; } ) ;

Nothing different here, just another plain test. Running this in Mocha you will get an error that the search doesnt have any methods, basically because we haven't written anything in it. So let's go add an outline with the function: 1 2 3 4 5 6 7 v a rf s=r e q u i r e ( " f s " ) ; e x p o r t s=m o d u l e . e x p o r t s={ } ; e x p o r t s . s c a n=f u n c t i o n ( d i r ,d e p t h ,d o n e ){ }

If you now run Mocha again, it will pause waiting for this async function to return, but since we haven't called the callback at all, the test will just timeout. By default it should time out after about two seconds, but you can adjust this using t h i s . t i m e o u t ( m i l l i s e c o n d s )inside of a describe or it block, to adjust their timeouts respectively. This scan function is supposed to take a path and depth, and return a list of all the files it finds. This is actually kind of tricky when you start thinking about how we are essentially recursing two different functions together in a single function. We need to recurse through the different folders and then those folders need to scan themselves and decide on going further. Doing this synchronously is fine because you can kind of step through it one by one, slowly completing one level or path at a time. When dealing with an async version it get's a bit more complicated because you can't just do a f o r e a c hloop or something, because it won't pause in between folders, they will all essentially run at the same time each returning different values and they would sort of overwrite each other. So to make it work, you need to create a sort of stack where you can asynchronously process one at a time (or
http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/ 13/17

1/14/2014

Testing in Node.js | Nettuts+

all at once if you use a queue instead) and then keep some order in that manner. It's a very specific algorithm so I just keep a snippet by Christopher Jeffrey which you can find on Stack Overflow. It doesn't apply just to loading files, but I have used this in a number of applications, basically anything where you need to process an array of objects one at a time using async functions. We need to alter it a bit, because we would like to have a depth option, how the depth option works is you set how many levels of folders you want to check, or zero to recurs indefinitely. Here is the completed function using the snippet: 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 2 6 2 7 2 8 2 9 e x p o r t s . s c a n=f u n c t i o n ( d i r ,d e p t h ,d o n e ){ d e p t h ; v a rr e s u l t s=[ ] ; f s . r e a d d i r ( d i r ,f u n c t i o n ( e r r ,l i s t ){ i f( e r r )r e t u r nd o n e ( e r r ) ; v a ri=0 ; ( f u n c t i o nn e x t ( ){ v a rf i l e=l i s t [ i + + ] ; i f( ! f i l e )r e t u r nd o n e ( n u l l ,r e s u l t s ) ; f i l e=d i r+' / '+f i l e ; f s . s t a t ( f i l e ,f u n c t i o n ( e r r ,s t a t ){ i f( s t a t& &s t a t . i s D i r e c t o r y ( ) ){ i f( d e p t h! = =0 ){ v a rn d e p t h=( d e p t h>1 )?d e p t h 1:1 ; e x p o r t s . s c a n ( f i l e ,n d e p t h ,f u n c t i o n ( e r r ,r e s ){ r e s u l t s=r e s u l t s . c o n c a t ( r e s ) ; n e x t ( ) ; } ) ; }e l s e{ n e x t ( ) ; } }e l s e{ r e s u l t s . p u s h ( f i l e ) ; n e x t ( ) ; } } ) ; } ) ( ) ; } ) ; } ;

Mocha should now be passing both tests. The last function we need to implement is the one which will accept an array of paths and a search keyword and return all matches. Here is the test for it: 1 2 3 4 5 6 7 8 d e s c r i b e ( " # m a t c h ( ) " ,f u n c t i o n ( ) { i t ( " s h o u l df i n da n dr e t u r nm a t c h e sb a s e do naq u e r y " ,f u n c t i o n ( ) { v a rf i l e s=[ " h e l l o . t x t " ," w o r l d . j s " ," a n o t h e r . j s " ] ; v a rr e s u l t s=s e a r c h . m a t c h ( " . j s " ,f i l e s ) ; e x p e c t ( r e s u l t s ) . t o . d e e p . e q u a l ( [ " w o r l d . j s " ," a n o t h e r . j s " ] ) ; r e s u l t s=s e a r c h . m a t c h ( " h e l l o " ,f i l e s ) ; e x p e c t ( r e s u l t s ) . t o . d e e p . e q u a l ( [ " h e l l o . t x t " ] ) ;
14/17

http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/

1/14/2014

Testing in Node.js | Nettuts+

9 1 0

} ) ;

} ) ;

And last but not least, let's add the function to s e a r c h . j s : 1 2 3 4 5 6 7 8 9 e x p o r t s . m a t c h=f u n c t i o n ( q u e r y ,f i l e s ) { v a rm a t c h e s=[ ] ; f i l e s . f o r E a c h ( f u n c t i o n ( n a m e ){ i f( n a m e . i n d e x O f ( q u e r y )! = =1 ){ m a t c h e s . p u s h ( n a m e ) ; } } ) ; r e t u r nm a t c h e s ; }

Just to make sure, run Mocha again, you should have a total of seven tests all passing.

Putting It All Together


The last step is to really write the glue code which pulls all our modules together; so in the root of our project add a file named a p p . j sor something like that and add the following inside: 1 2 3 4 5 6 7 8 9 1 0 1 1 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3 2 4 2 5 #! / u s r / b i n / e n vn o d e v a rt a g s=r e q u i r e ( " . / l i b / t a g s . j s " ) ; v a rs e a r c h=r e q u i r e ( " . / l i b / s e a r c h . j s " ) ; v a rd e f a u l t s={ p a t h :" . " , q u e r y :" " , d e p t h :2 } v a rr e p l a c e m e n t s={ p :" p a t h " , q :" q u e r y " , d :" d e p t h " , h :" h e l p " } t a g s=t a g s . p a r s e ( p r o c e s s . a r g v ,d e f a u l t s ,r e p l a c e m e n t s ) ; i f( t a g s . h e l p ){ c o n s o l e . l o g ( " U s a g e :. / a p p . j sq = q u e r y[ d = d e p t h ][ p = p a t h ] " ) ; }e l s e{ s e a r c h . s c a n ( t a g s . p a t h ,t a g s . d e p t h ,f u n c t i o n ( e r r ,f i l e s ){ s e a r c h . m a t c h ( t a g s . q u e r y ,f i l e s ) . f o r E a c h ( f u n c t i o n ( f i l e ) { c o n s o l e . l o g ( f i l e ) ; } ) ;
15/17

http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/

1/14/2014

Testing in Node.js | Nettuts+

2 6 2 7

} ) ;

No actual logic going on here really, we are just basically connecting the different modules together to get the desired results. I usually don't test this code as it's just glue code which has all been tested already. You can now make your script executable (c h m o d+ xa p p . j son a Unix system) and then run it like so: 1 . / a p p . j sq = " . j s "

Optionally customizing some of the other placeholders we setup.

Conclusion
In this article we have built an entire file searching app, albeit a simple one, but I think it demonstrates the process as a whole fairly well. Some personal advice moving forward; if you are going to do a lot of TDD, setup your environment. A lot of the overhead time people associate with TDD is due to them having to keep switching windows around, opening and closing different files, then running tests and repeating this 80 dozen times a day. In such a case it interrupts your workflow decreasing productivity. But if you have your editor setup, like you either have the tests and code sideby-side or your IDE supports jumping back and forth, this saves a ton of time. You can also get your tests to automatically run by calling it with the wtag to watch the files for changes and auto run all tests. These kinds of things make the process more seamless and more of an aid then a bother. I hope you enjoyed this article, if you have any questions you can leave them below, contact me on Twitter @gabrielmanricks or on the Nettuts+ IRC channel (#nettuts on freenode).
Like 62 people like this.

Tags: ChainodeTesting

By Gabriel Manricks
I'm a freelance web developer with experience spanning the full stack of application development and a senior writer here at NetTuts+. Besides for that I spend my time writing books for Packt or working on open source projects I find intriguing . You can find me on Twitter @gabrielmanricks or visit my site to see all the things I'm working on gabrielmanricks.com.

http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/

16/17

1/14/2014

Testing in Node.js | Nettuts+

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more

http://net.tutsplus.com/tutorials/javascript-ajax/testing-in-node-js/

17/17

Você também pode gostar