Đ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 30', 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ả | 12.4 Making Get Requests 263 var url url ajax.get url assertEquals GET url true this.xhr.open.args Much better. Re-running the tests confirm that they now all pass. Moving forward we can add stubs to the fakeXMLHttpRequest object as we see fit which will make testing ajax.get significantly simpler. 12.4.2.4 Feature Detection and ajax.create ajax.get now relies on the ajax.create method which is not available in the case that the browser does not support the XMLHttpRequest object. To make sure we don t provide an ajax.get method that has no way of retrieving a transport we will define this method conditionally as well. Listing 12.27 shows the required test. Listing 12.27 Bailing out if ajax.create is not available function var ajax tddjs.namespace ajax if ajax.create return function get url . ajax.get get With this test in place clients using the ajax.get method can add a similar test to check for its existence before using it. Layering feature detection this way makes it manageable to decide what features are available in a given environment. 12.4.3 Handling State Changes Next up the XMLHttpRequest object needs to have its onreadystatechange handler set to a function as Listing 12.28 shows. Download from www.eBookTM.com 264 Abstracting Browser Differences Ajax Listing 12.28 Verifying that the ready state handler is assigned test should add onreadystatechange handler function ajax.get url assertFunction this.xhr.onreadystatechange As expected the test fails because xhr.onreadystatechange is undefined. We can assign an empty function for now as Listing 12.29 shows. Listing 12.29 Assigning an empty onreadystatechange handler function get url . transport.onreadystatechange function To kick off the request we need to call the send method. This means that we need to add a stubbed send method to fakeXMLHttpRequest and assert that it was called. Listing 12.30 shows the updated object. Listing 12.30 Adding a stub send method var fakeXMLHttpRequest open stubFn send stubFn .