7

I'm working on a nodejs application. I managed to break some of the code in separate modules, that I'm testing using nodeunit, but a substantial part of my code base still relies on socket.io.

How can I test my socket.io events?

vise
  • 12,713
  • 11
  • 52
  • 64
  • Was the linked article sufficient, or have you opted for a different approach? – Andy Oct 18 '11 at 12:42
  • Thanks for asking. The article looks ok, but I'm not entirely sure this is the way to go. As far as I can tell the link you provided tests what the server is sending, but the logic in my code actually does a lot of stuff in the backend which is not immediately visible to the clients. As I mentioned, I moved some of it into stand alone modules, but there are still some parts that are untested which I'm afraid will fail silently when I least expect them sometime in the unforeseen future. So while I can still make the solution you provided me work, I feel that there's an awful lot of work needed. – vise Oct 18 '11 at 19:22
  • Sounds like a good candidate for Jasmine's Spies - answer updated. – Andy Oct 19 '11 at 09:51

1 Answers1

8

Try this article: Socket.IO and Asynchronous Testing with node.js.

So, let's fake. I mean, let's create fake instances of the contender servers, as well as the visualization client. Then, we'll build a test suite that uses these fakes to test-drive the actual server we're developing. I'll paste some slightly simplified pieces of code here for example. If you are really interested in the stuff, you'll find it all on Github.

edit: if you need to test functionality for which there is no immediate output, Jasmine BDD provides spies. These can be used to "see inside" a function and test whether certain parameters are passed etc, and are useful for mocking asynchronous calls for testing, as well as writing more functional tests:

Jasmine Spies are test doubles that can act as stubs, spies, fakes or when used in an expecation, mocks...Spies can be checked if they were called or not and what the calling params were. A Spy has the following fields: wasCalled, callCount, mostRecentCall, and argsForCall (see docs). Spies are torn down at the end of every spec.

Docs, an article and a related SO question.

Community
  • 1
  • 1
Andy
  • 17,423
  • 9
  • 52
  • 69