Đ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 39', 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.2 The Controller 353 Unfortunately this doesn t play out exactly as planned. The previous test which also calls post is now attempting to call addMessage on chatRoom which is undefined in that test. We can fix the issue by moving the chatRoom stub into setUp as Listing 14.18 does. Listing 14.18 Sharing the chatRoom stub function controllerSetUp . this.controller.chatRoom addMessage stub All the tests go back to a soothing green and we can turn our attention to the duplicated logic we just introduced in the second test. In particular both tests simulates sending a request with a body. We can simplify the tests considerably by extracting this logic into the setup. Listing 14.19 shows the updated tests. Listing 14.19 Cleaning up post tests function controllerSetUp . this.sendRequest function data var str encodeURI JSON.stringify data this.req.emit data str.substring 0 str.length 2 this.req.emit data str.substring str.length 2 this.req.emit end testCase exports chatRoomController.post . should parse request body as JSON function test var data data user cjno message hi JSON.parse stub data this.controller.post this.sendRequest data test.equals JSON.parse.args 0 JSON.stringify data test.done . Download from www.eBookTM.com 354 Server-Side JavaScript with Node.js The cleaned up tests certainly are a lot easier to follow and with the sendRequest helper method writing new tests that make requests will be easier as well. All tests pass and we can move on. 14.2.4.3 Malicious Data Notice that we are currently accepting messages completely unfiltered. This can lead to all kinds of scary situations for instance consider the effects of the request in Listing 14.20 Listing 14.20 Malicious request topic message data user cjno message script window.location http hacked script Before deploying an application like the one we are currently building we should take care to not blindly accept any end user data unfiltered. 14.2.5 Responding to Requests When the controller has added the