small medium large xlarge

21 Jul 2016, 22:02
Erin McKean (2 posts)

Hi! I’m finding Test-Driving JavaScript Applications extremely useful, thanks so much for writing it!

I’m working on adding tests to a fairly large existing Express app to speed up future development. However, I’m having some trouble testing the routes, because they call functions in separate files, e.g., instead of:

routes.get('/') function(req, res) {
 //function body here

the functions live in separate files, e.g.

routes.get('/', datafree.home);

When trying to stub those router functions, I get a lovely “undefined is not a function” error. :)

Can you suggest a solution for testing these routes? Should I just test the target functions, and not the routes?

Any help gratefully appreciated!

22 Jul 2016, 12:28
Venkat Subramaniam (99 posts)

Hi Erin,

Thank you for the kind words, thrilled to hear that you find the book useful.

In the case you’ve mentioned, the routes.get is registering datafree.home as the handler for “/”.

When testing routes we do two things:

  1. Verify that the function is registering a desired handler using the desired method (GET, POST, etc.).

  2. Verify that the handler is doing the right things.

In the case you’ve mentioned, the second test can be directly on datafree.home. We do not have to go through the routes for that. For the first test, we can stub out the Router and verify that it is passing datafree.home as the second parameter. In other words, instead of

expect(router.get.calledWith('/', sandbox.match.any));

we may do something like:

expect(router.get.calledWith('/', datafree.home));

Please give that a try and if you’re running into trouble, I will be glad to take a look at a sample you create to see what’s going on.

Hope this is helpful.



22 Jul 2016, 21:14
Erin McKean (2 posts)

Thanks! This works great, I just had to remember to require the ‘datafree.js’ file as well!

Thanks again for your help and for writing such a clear and useful book!



You must be logged in to comment