javascript - How to fail test if response from server is given? -
i working on socket.io irc , don't want users have long username. wrote following (mocha) test verify server doesn't send out response every connected socket when longer username provided:
it("should not accept usernames longer 15 chars", function (done) { var username = "a".repeat(server.getmaxusernamelength() + 1); client1.emit("username change", username); client2.on("chat message", function (data) { throw error("fail, server did send response."); }); settimeout(function () { done(); }, 50); });
this work, it's far optimal. if ci platform slower or server respond after more 50 ms? what's best way fail test when response given, or should structure tests differently?
thanks!
p.s. question different testing asynchronous function mocha, because while problem have asynchronous testing, aware of done() method (and i'm using obviously).
what you're trying verify callback client2.on("chat message"...
never called. testing negative cases can tough, , case seems exacerbated fact you're trying complete end-to-end (client-to-server-to-client) integration test. personally, try test in unit case suite , avoid introducing complexity of asynchronicity test.
however, if must done, here's tip eradicating non-determinism in tests:
this trickiest case since can test expected response, there's nothing detect failure other timing-out. if provider you're building can handle ensuring provider implements way of indicating it's done - form of callback. if testing code uses it, it's worth - although you'll find kind of functionality valuable other purposes too.
your server should send sort of notice client1
it's going ignore name change, if aren't testing, since you use such notification verify didn't send notification other client. like:
it("should not accept usernames longer 15 chars", function (done) { var chatspy = sinon.spy(); client2.on("chat message", chatspy); client1.on('error', function(err) { assertequals(err.msg, 'username long'); assert(chatspy.nevercalledwith(...)); done(); }); var username = "a".repeat(server.getmaxusernamelength() + 1); client1.emit("username change", username); });
would suitable.
also, if whatever reason, server.getmaxusernamelength()
ever starts returning other 15
, best case scenario test description becomes wrong. can become worse if getmaxusernamelength
, server code handling name change event don't values same place. test should not rely on system under test provide test values.
Comments
Post a Comment