Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'phát triển javascript - part 40', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 14.3 Domain Model and Storage 363 The test exposes our cheat so we need to find a better way to generate ids. Listing 14.39 uses a simple variable that is incremented each time a message is added. Listing 14.39 Assigning unique integer ids var id 0 var chatRoom addMessage function user message callback . if err data id id user user message message . Tests are passing again. You might worry that we re not actually storing the message anywhere. That is a problem but it s not currently being addressed by the test case. To do so we must start testing message retrieval. 14.3.4 Fetching Messages In the next chapter we will interface with the chat backend using the cometClient from Chapter 13 Streaming Data with Ajax and Comet. This means that chatRoom needs some way to retrieve all messages since some token. We ll add a getMessagesSince method that accepts an id and yields an array of messages to the callback. 14.3.4.1 The getMe ssagesSince Method The initial test for this method in Listing 14.40 adds two messages then tries to retrieve all messages since the id of the first. This way we don t program any assumptions about how the ids are generated into the tests. Listing 14.40 Testing message retrieval testCase exports chatRoom.getMessagesSince should get messages since given id function test var room Object.create chatRoom var user cjno Download from www.eBookTM.com 364 Server-Side JavaScript with Node.js room.addMessage user msg function e first room.addMessage user msg2 function e second room.getMessagesSince first.id function e msgs test.isArray msgs test.same msgs second test.done The test fails in the face of a missing getMessagesSince. Listing 14.41 adds an empty method that simply calls the callback without arguments. Listing 14.41 Adding getMessagesSince var chatRoom addMessage function user message callback . getMessagesSince function id callback callback Because addMessage isn t really storing the messages anywhere there s no way for getMessagesSince to .