Hi Martin

I was asking myself these very same questions about a year ago. What
really helped me get my head around unit testing was to read Misko
Hevery's guide to testable code: http://bit.ly/GNymAe. While the
examples are in Java, the same principles apply: embrace the Single
Responsibility Principle (SRP), leverage Dependency Injection (DI), and
isolate logic using Mock Objects.

I test-drove an example of a UserAuthenticator class using these ideas
here: http://bit.ly/GNmDeQ. I tried to emulate your dependencies as
much as possible (UserRepository class). It uses Jasmine for the unit 
tests. You
can use jasmine-node (https://github.com/mhevery/jasmine-node) to run
these locally.

-Rehan

On Friday, March 23, 2012 3:35:03 PM UTC-7, Martin Lundberg wrote:
>
> Hi!
>
> I'm having problems getting up and running with testing my node.js code.
>
> I've got a file called auth.js with a function that looks like: 
> authenticate(email, password, callback). The authenticate function tries to 
> fetch a user with the given e-mail using a collaborator UserRepository 
> object. It runs a function like: user = users.get({ email: email }, 
> function(user) { ... }) where users is the UserRepository object. If it 
> gets a user and the password is correct it calls the callback function 
> like: callback(null, user) but if it don't get a user or if the password is 
> incorrect it calls the callback sending an error as the first parameter.
>
> When writing unit tests the authenticate method (and all the other 
> functions in auth.js) I don't want to use the real UserRepository (which in 
> turn uses a database library like node-mysql) object and a real database. I 
> believe I should create a stub and define return values so I can see that 
> authenticate returns correct values when it gets a user and when it don't. 
> The problems is that I've read a lot of tutorials and articles about 
> mocking and testing but I still don't understand how I should do this in a 
> good way.
>
> I hope the text isn't too confusing. I would really appreciate some 
> guiding in this area so I can get started testing my apps in a good way.
>
> Regards,
>
> Martin Lundberg
>
>

-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

Reply via email to