I'm writing a simplistic TCP server using Node.JS in order to learn more about some specific things before I take on a larger project that I have in mind. I'm hoping to learn more about test-driven-development, user authentication and encryption along the way. For kicks, I'm implementing a multiplayer tic-tac-toe game with user accounts, statistics, and random game pairing.
Anyway.
My question is, I have tests set up for some parts of the application, but it's come time to write the TCP portion. I'm using Expresso in combination with Should.js, and it's working great. My question is how exactly do I test a TCP server? Do I make repeated requests and make sure I'm getting back the things I'm wanting? Or should I somehow write the server in ways that it can be tested without having to make requests in the first place? (through abstraction)
I'm seriously curious. Thanks in advance for the insight!
Node.js makes this really easy. You can create your server right in your test method and create a client to connect in that test method. It'll turn out very clean.
Your client/server communication will have some sort of messaging/communication contract. So, to TDD this thing, you'll start with each message/dataset, etc and write tests for that. I like to have Server encapsulate a TCP server so that it can perform custom logic.
So you might have something like this:
Test1:
describe('MyServer', function(){
it('should respond with an acknowledgment of receiving my move command', function(done){
var server = new MyServer();
server.listen(9000);
var json = '{"player": "1", "tile": "3"}' //player 1 puts an 'X' in tile 3
client = net.connect(9000, function(){
client.write(json);
});
client.on('data', function(data){
//** your tests here to validate YOUR CUSTOM server response **
//example assuming your server sends JSON
serverResponse = JSON.parse(data.toString());
assert(serverResponse.tilesRemainingCount, 5); //completely custom
server.close();
done();
});
});
}
Does that help at all? That's how I've been doing it, and it works great. Let me know if something's not clear and I'll try to clear it up.
Also, I'm a CoffeeScript dev, so I may have made an error with JS syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With