Phát triển Javascript - part 28 pps

10 215 0
Phát triển Javascript - part 28 pps

Đang tải... (xem toàn văn)

Thông tin tài liệu

ptg 11.7 Observing Arbitrary Events 243 other two functions (and their tests) as an exercise. When you are done you will note that one of the tests keep failing. We will deal with that last test together. 11.7.2 Supporting Events in notify While updating notify to accept an event whose observers to notify, one of the existing tests stays in the red. The test in question is the one that compares arguments sent to notify against those received by the observer. The problem is that because notify simply passes along the arguments it receives, the observer is now receiving the event name in addition to the arguments it was supposed to receive. To pass the test, Listing 11.44 uses Array.prototype.slice to pass along all but the first argument. Listing 11.44 Passing all but the first argument to observers function notify(event) { /* */ var args = Array.prototype.slice.call(arguments, 1); for (var i = 0, l = this.observers.length; i < l; i++) { try { this.observers[i].apply(this, args); } catch (e) {} } } This passes the test and now observable has the interface to support events, even if it doesn’t actually support them yet. The test in Listing 11.45 specifies how the events are supposed to work. It registers two observers to two different events. It then calls notify for only one of the events and expects only the related observer to be called. Listing 11.45 Expecting only relevant observers to be called "test should notify relevant observers only": function () { var calls = []; this.observable.observe("event", function () { calls.push("event"); }); this.observable.observe("other", function () { From the Library of WoweBook.Com Download from www.eBookTM.com ptg 244 The Observer Pattern calls.push("other"); }); this.observable.notify("other"); assertEquals(["other"], calls); } The test obviously fails as the observable happily notifies all the observers. There is no trivial way to fix this, so we roll up our sleeves and replace the observable array with an object. The new object should store observers in arrays on properties whose keys are event names. Rather than conditionally initializing the object and array in all the methods, we can add an internal helper function that retrieves the correct array for an event, creating both it and the object if necessary. Listing 11.46 shows the updated implementation. Listing 11.46 Storing observers in an object rather than an array (function () { function _observers(observable, event) { if (!observable.observers) { observable.observers = {}; } if (!observable.observers[event]) { observable.observers[event] = []; } return observable.observers[event]; } function observe(event, observer) { if (typeof observer != "function") { throw new TypeError("observer is not function"); } _observers(this, event).push(observer); } function hasObserver(event, observer) { var observers = _observers(this, event); for (var i = 0, l = observers.length; i < l; i++) { From the Library of WoweBook.Com Download from www.eBookTM.com ptg 11.7 Observing Arbitrary Events 245 if (observers[i] == observer) { return true; } } return false; } function notify(event) { var observers = _observers(this, event); var args = Array.prototype.slice.call(arguments, 1); for (var i = 0, l = observers.length; i < l; i++) { try { observers[i].apply(this, args); } catch (e) {} } } tddjs.namespace("util").observable = { observe: observe, hasObserver: hasObserver, notify: notify }; }()); Changing the entire implementation in one go is a bit of a leap, but given the small size ofthe interface, we took a chance, and according to the tests, we succeeded. If you are uncomfortable making such a big change in one go, you can take smaller steps. The clue to performing structural refactorings like this in small steps is to build the new functionality side-by-side with the old and remove the old one first when the new one is complete. To make the change we just made using smaller steps, you could introduce the object backend using another name and add observers both to this and the old array. Then, you could update notify to use the new object, passing the last test we added. From there you could write more tests, e.g., for hasObserver, and switch over from the array to the object piece by piece. When all the methods were using the object, you could remove the array and possibly rename the object. The internal helper function we added could be the result of refactoring away duplication. As an exercise, I encourage you to improve the test case—find edge cases and weak points, document them in tests and if you find problems, update the implementation. From the Library of WoweBook.Com Download from www.eBookTM.com ptg 246 The Observer Pattern 11.8 Summary Through a series of small steps, we have managed to write a library that implements a design pattern, ready for use in our projects. We have seen how tests can help make design decisions, how tests form requirements, and how tests can help solve nasty bugs—even cross-browser related ones. While developing the library we have gotten some basic practice writing tests and letting tests guide us through writing production code. We have also exercised our refactoring muscles thoroughly. By starting out with the simplest thing that could possibly work we have gained a good understanding of the important role of refactoring in test-driven development. It is through refactoring, both in production code and tests, that our solutions can grow refined and elegant. In the next chapter we will deal more closely with browser inconsistencies as we dig into the mechanics of “Ajax”, using test-driven development to implement a higher level interface on top of the XMLHttpRequest object. From the Library of WoweBook.Com Download from www.eBookTM.com ptg 12 Abstracting Browser Differences: Ajax A jax, (asynchronous JavaScript and XML) is a marketing term coined to describe client technologies used to create rich internet applications, with the XMLHttpRequest object at the center stage. It’s used heavily across the web, usually through some JavaScript library. In this chapter we will get to know XMLHttpRequest better by implementing our own higher level API using test-driven development. Doing so will allow us to touch ever so lightly on the inner workings of an “ajax call”; it will teach us how to use test-driven development to abstract browser inconsistencies; and most impor- tantly, it will give us an introduction to the concept of stubbing. The API we will build in this chapter will not be the ultimate XMLHttp- Request abstraction, but it will provide a bare minimum to work with asyn- chronous requests. Implementing just what we need is one of the guiding principles of test-driven development, and paving the road with tests will allow us to go just as far as we need, providing a solid base for future extension. 12.1 Test Driving a Request API Before we get started, we need to plan how we will be using test-driven development to abstract browser inconsistencies. TDD can help discover inconsistencies to some degree, but the nature of some bugs are so obscure that unit tests are unlikely to discover them all by accident. 247 From the Library of WoweBook.Com Download from www.eBookTM.com ptg 248 Abstracting Browser Differences: Ajax 12.1.1 Discovering Browser Inconsistencies Because unit tests are unlikely to accidentally discover all kinds of browser bugs, some amount of exploration is necessary to uncover the bugs we’re abstracting. However, unit tests can help us make sure we cover the holes by triggering offending behavior from within tests and making sure that production code copes with these situations. Incidentally, this is the same way we usually use unit tests to “capture” bugs in our own logic. 12.1.2 Development Strategy We will build the Ajax interface bottom up, starting by asserting that we can get a hold of an XMLHttpRequest object from the browser. From there we will focus on individual features of the object only. We will not make any server side requests from within the unit tests themselves, because doing so will make the tests harder to run (we’ll need someone answering those requests) and it makes it harder to test isolated behavior. Unit tests are there to drive us through development of the higher level API. They are going to help us develop and test the logic we build on top of the native transport, not the logic a given browser vendor built into their XMLHttpRequest implementation. Testing our own logic is all fine and dandy, but we still need to test that the implementation really works when sitting on top of an actual XMLHttpRequest object. To do this, we will write an integration test once the API is usable. This test will be the real deal; it will use our interface to make requests to the server. By running it from an HTML file in the browser, we can verify that it either works or fails gracefully. 12.1.3 The Goal The decision to write an XMLHttpRequest wrapper without actually using it inside the tests may sound strange at first, but allow me to remind you yet again of the goal of test-driven development; TDD uses tests as a design tool whose main purpose is to guide us through development. In order to truly focus on units in isolation, we need to eliminate external dependencies as much as practically possible. For this purpose we will use stubs extensively in this chapter. Remember that our main focus is to learn test-driven development, meaning that we should concentrate on the thought process and how tests form requirements. Additionally, we will keep practicing continuous refactoring to improve the implementation, API, and tests. Stubbing is a powerful technique that allows true isolation of the system under test. Stubs (and mocks) have not been discussed in detail thus far, so this chapter From the Library of WoweBook.Com Download from www.eBookTM.com ptg 12.2 Implementing the Request Interface 249 will serve as a test-driven introduction to the topic. JavaScript’s dynamic nature enables us to stub manually without too much hassle. However, when we are done with this chapter we will get a better overview of patterns that would be helpful to have automated, even in the dynamic world of JavaScript. Chapter 16, Mocking and Stubbing, will provide a more complete background on both stubs and mocks, but you should be able to follow the examples in this and following chapters without any prior experience with them. 12.2 Implementing the Request Interface As in Chapter 11, The Observer Pattern, we will use JsTestDriver to run tests for this project. Please refer to Chapter 3, Tools of the Trade, for an introduction and installation guide. 12.2.1 Project Layout The project layout can be seen in Listing 12.1 and the contents of the JsTestDriver configuration file are found in Listing 12.2. Listing 12.1 Directory layout for the ajax project chris@laptop:~/projects/ajax $ tree . | jsTestDriver.conf | lib | ' tdd.js | src | ' ajax.js | ' request.js ` test ' ajax_test.js ' request_test.js Listing 12.2 The jsTestDriver.conf file server: http://localhost:4224 load: - lib/*.js - src/*.js - test/*.js From the Library of WoweBook.Com Download from www.eBookTM.com ptg 250 Abstracting Browser Differences: Ajax The tdd.js file should contain the utilities built in Part II, JavaScript for Programmers. The initial project state can be downloaded off the book’s website 1 for your convenience. 12.2.2 Choosing the Interface Style The first thing we need to decide is how we want to implement the request interface. To make an informed decision, we need a quick reminder on how a basic XML- HttpRequest works. The following shows the bare minimum of what needs to be done (order matters). 1. Create an XMLHttpRequest object. 2. Call the open method with the desired HTTP verb, the URL, and a boolean indicating whether the request is asynchronous or not; true means asynchronous. 3. Set the object’s onreadystatechange handler. 4. Call the send method, passing in data if any. Users of the high-level interface shouldn’t have to worry about these details. All we really need to send a request is a URL and the HTTP verb. In most cases the ability to register a response handler would be useful as well. The response handler should be available in two flavors: one to handle successful requests and one to handle failed requests. For asynchronous requests, the onreadystatechange handler is called asynchronously whenever the status of the request is updated. In other words, this is where the request eventually finishes, so the handler needs some way to access the request options such as callbacks. 12.3 Creating an XMLHttpRequest Object Before we can dive into the request API, we need a cross-browser way to obtain an XMLHttpRequest object. The most obvious “Ajax” browser inconsistencies are found in the creation of this very object. 1. http://tddjs.com From the Library of WoweBook.Com Download from www.eBookTM.com ptg 12.3 Creating an XMLHttpRequest Object 251 12.3.1 The First Test The very first test we will write is the one that expects an XMLHttpRequest object. As outlined in Section 12.2.2, Choosing the Interface Style, the properties we rely on are the open and send methods. The onreadystatechange handler needs the readyState property to know when the request has finished. Last, but not least, we will eventually need the setRequestHeader method in order to, well, set request headers. Listing 12.3 shows the test in full; save it in test/ajax _ test.js. Listing 12.3 Testing for an XMLHttpRequest object TestCase("AjaxCreateTest", { "test should return XMLHttpRequest object": function () { var xhr = tddjs.ajax.create(); assertNumber(xhr.readyState); assert(tddjs.isHostMethod(xhr, "open")); assert(tddjs.isHostMethod(xhr, "send")); assert(tddjs.isHostMethod(xhr, "setRequestHeader")); } }); This test fails as expected because there is no tddjs.ajax namespace. Listing 12.4 shows the namespace declaration that goes in src/ajax.js. In order for this to run, the tddjs.namespace method from Chapter 6, Applied Functions and Closures, needs to be available in lib/tdd.js. Listing 12.4 Creating the ajax namespace tddjs.namespace("ajax"); With this in place the test fails in response to the missing create method. We will need a little background before we can implement it. 12.3.2 XMLHttpRequest Background Microsoft invented XMLHttpRequest as an ActiveX object back in 1999. Com- petitors followed suit shortly after, and today the object is available in just about every current browser. It’s even on its way to becoming a W3C standard, in Last Call Working Draft at the time of writing. Listing 12.5 shows how the object is From the Library of WoweBook.Com Download from www.eBookTM.com ptg 252 Abstracting Browser Differences: Ajax created in the defacto standards mode versus the ActiveXObject in Internet Explorer. Listing 12.5 Instantiating the XMLHttpRequest object // Proposed standard / works in most browsers var request = new XMLHttpRequest(); // Internet Explorer 5, 5.5 and 6 (also available in IE 7) try { var request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("ActiveX is disabled"); } Internet Explorer 7 was the first Microsoft browser to provide a quasi-native XMLHttpRequest object, although it also provides the ActiveX object. Both ActiveX and IE7’s native object can be disabled by users or system administra- tors though, so we need to be careful when creating the request. Additionally, the “native” version in IE7 is unable to make local file requests, so we will prefer the ActiveX object if it’s available. The ActiveX object identificator, “Microsoft.XMLHTTP” in Listing 12.5, is known as an ActiveX ProgId. There are several available ProgId’s for the XMLHttpRequest object, corresponding to different versions of Msxml: • Microsoft.XMLHTTP • Msxml2.XMLHTTP • Msxml2.XMLHTTP.3.0 • Msxml2.XMLHTTP.4.0 • Msxml2.XMLHTTP.5.0 • Msxml2.XMLHTTP.6.0 In short, Microsoft.XMLHTTP covers IE5.x on older versions of Win- dows, versions 4 and 5 are not intended for browser use, and the three first ProgId’s will in most setups refer to the same object—Msxml2.XMLHTTP.3.0. Finally, some clients may have Msxml2.XMLHTTP.6.0 installed side-by-side with Msxml2.XMLHTTP.3.0 (which comes with IE 6). This means that ei- ther Msxml2.XMLHTTP.6.0 or Microsoft.XMLHTTP is sufficient to re- trieve the newest available object in Internet Explorer. Keeping things simple, From the Library of WoweBook.Com Download from www.eBookTM.com . Msxml2.XMLHTTP.6.0 installed side-by-side with Msxml2.XMLHTTP.3.0 (which comes with IE 6). This means that ei- ther Msxml2.XMLHTTP.6.0 or Microsoft.XMLHTTP is sufficient to re- trieve the newest available. request_test.js Listing 12.2 The jsTestDriver.conf file server: http://localhost:4224 load: - lib/*.js - src/*.js - test/*.js From the Library of WoweBook.Com Download from www.eBookTM.com ptg 250 Abstracting. ultimate XMLHttp- Request abstraction, but it will provide a bare minimum to work with asyn- chronous requests. Implementing just what we need is one of the guiding principles of test-driven development,

Ngày đăng: 04/07/2014, 22:20

Tài liệu cùng người dùng

Tài liệu liên quan