Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Test Driven JavaScript Development- P20:This book is about programming JavaScript for the real world, using the techniques and workflow suggested by Test-Driven Development. It is about gaining confidence in your code through test coverage, and gaining the ability to fearlessly refactor and organically evolve your code base. It is about writing modular and testable code. It is about writing JavaScript that works in a wide variety of environments and that doesn’t get in your user’s way. | 14.5 Event Emitters 373 Listing 14.54 Expecting chatRoom to be event emitter testCase exports chatRoom should be event emitter function test test.isFunction chatRoom.addListener test.isFunction chatRoom.emit test.done We can pass this test by popping EventEmitter.prototype in as chatRoom s prototype as seen in Listing 14.55. Listing 14.55 chatRoom inheriting from EventEmitter.prototype . var EventEmitter require events .EventEmitter . var chatRoom Object.create EventEmitter.prototype chatRoom.addMessage function user message . chatRoom.getMessagesSince function id . Note that because V8 fully supports ECMAScript 5 s Object.create we could have used property descriptors to add the methods as well as seen in Listing 14.56. Listing 14.56 chatRoom defined with property descriptors var chatRoom Object.create EventEmitter.prototype addMessage value function user message . getMessagesSince value function id . Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. From the Library of WoweBook.Com 374 Server-Side JavaScript with Node.js At this point the property descriptors don t provide anything we have a documented need for i.e. the ability to override default property attribute values so we ll avoid the added indentation and stick with the simple assignments in Listing 14.55. Next up we make sure that addMessage emits an event. Listing 14.57 shows the test. Listing 14.57 Expecting addMessage to emit a message event testCase exports chatRoom.addMessage . should emit message event function test var message this.room.addListener message function m message m this.room.addMessage cjno msg .then function m test.same m message test.done To pass this test we need to place a call to emit right before we resolve the promise as seen in Listing 14.58. Listing 14.58 Emitting a message event chatRoom.addMessage function user message callback var promise new Promise process.nextTick function . if err . this.emit message data promise.resolve data else .