Java Script Isn\'t a Toy Anymore

1,570 views
1,477 views

Published on

Automated testing of Java script inside of cloud computing applications written in visual force on the salesforce.com force.com platform.

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,570
On SlideShare
0
From Embeds
0
Number of Embeds
19
Actions
Shares
0
Downloads
14
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide
  • expect(x).toEqual(y); compares objects or primitives x and y and passes if they are equivalentexpect(x).toBeNull(); passes if x is nullexpect(x).toContain(y); passes if array or string x contains yexpect(x).toBeLessThan(y); passes if x is less than yexpect(x).toBeGreaterThan(y); passes if x is greater than yexpect(fn).toThrow(e); passes if function fn throws exception e when executed
  • expect(x).toHaveBeenCalled() passes if x is a spy and was calledexpect(x).toHaveBeenCalledWith(arguments) passes if x is a spy and was called with the specified argumentsexpect(x).not.toHaveBeenCalled() passes if x is a spy and was not calledexpect(x).not.toHaveBeenCalledWith(arguments) passes if x is a spy and was not called with the specified arguments
  • Spies have some useful properties:callCount: returns number of times spy was calledmostRecentCall.args: returns argument array from last call to spy.argsForCall[i] returns arguments array for call i to spy.Spies are automatically removed after each spec. They may be set in the beforeEach function.
  • The callBack() is not actually called by the asyncMethod() it is only used as a method parameterHowever we do call it ourselves and we access it by inspecting the arguments used by the most recent callThen we verify our expected that the callBack() has now been called
  • waitsFor() provides a better interface for pausing your spec until some other work has completed. Jasmine will wait until the provided function returns true before continuing with the next block. This may mean waiting an arbitrary period of time, or you may specify a maxiumum period in milliseconds before timing out:In this example, we create a spreadsheet and fill it with some sample data. We then ask the spreadsheet to start calculating its total, which presumably is a slow operation and therefore happens asynchronously. We ask Jasmine to wait until the spreadsheet’s calculation work is complete (or up to 10 seconds, whichever comes first) before continuing with the rest of the spec. If the calculation finishes within the allotted 10 seconds, Jasmine continues on to the final runs() block, where it validates the calculation. If the spreadsheet hasn’t finished calculations within 10 seconds, the spec stops and reports a spec failure with the message given in the waitsFor() block.In this example, we create a spreadsheet and fill it with some sample data. We then ask the spreadsheet to start calculating its total, which presumably is a slow operation and therefore happens asynchronously. We ask Jasmine to wait until the spreadsheet’s calculation work is complete (or up to 10 seconds, whichever comes first) before continuing with the rest of the spec. If the calculation finishes within the allotted 10 seconds, Jasmine continues on to the final runs() block, where it validates the calculation. If the spreadsheet hasn’t finished calculations within 10 seconds, the spec stops and reports a spec failure with the message given in the waitsFor() block.
  • Force failures are exactly what they sound like. You want to force a failure. You are able to pass along a specific error message to be output.
  • Some of the benefits of YUI testSome things you still need to deal with…
  • Nice thing is standardized way to mimic user inputs that works everywhere
  • Update your tests to run correctly in each browserYAHOO.env.ua.{browser}YAHOO.env.ua.gecko
  • I like the approach because we can save the data into a custom object for reporting purposes
  • Obvious benefits include creating new test executions relating user story record to test case
  • Java Script Isn\'t a Toy Anymore

    1. 1. JavaScript Is Not a ToyIt’s Time it was Tested<br />Developers<br />James Hatton : salesforce.com<br />Alexis Williams: salesforce.com<br />
    2. 2. Safe Harbor<br />Safe harbor statement under the Private Securities Litigation Reform Act of 1995: This presentation may contain forward-looking statements that involve risks, uncertainties, and assumptions. If any such uncertainties materialize or if any of the assumptions proves incorrect, the results of salesforce.com, inc. could differ materially from the results expressed or implied by the forward-looking statements we make. All statements other than statements of historical fact could be deemed forward-looking, including any projections of subscriber growth, earnings, revenues, or other financial items and any statements regarding strategies or plans of management for future operations, statements of belief, any statements concerning new, planned, or upgraded services or technology developments and customer contracts or use of our services.<br />The risks and uncertainties referred to above include – but are not limited to – risks associated with developing and delivering new functionality for our service, our new business model, our past operating losses, possible fluctuations in our operating results and rate of growth, interruptions or delays in our Web hosting, breach of our security measures, the outcome of intellectual property and other litigation, risks associated with possible mergers and acquisitions, the immature market in which we operate, our relatively limited operating history, our ability to expand, retain, and motivate our employees and manage our growth, new releases of our service and successful customer deployment, our limited history reselling non-salesforce.com products, and utilization and selling to larger enterprise customers. Further information on potential factors that could affect the financial results of salesforce.com, inc. is included in our annual report on Form 10-K for the most recent fiscal year ended January 31, 2010. This documents and others are available on the SEC Filings section of the Investor Information section of our Web site. <br />Any unreleased services or features referenced in this or other press releases or public statements are not currently available and may not be delivered on time or at all. Customers who purchase our services should make the purchase decisions based upon features that are currently available. Salesforce.com, inc. assumes no obligation and does not intend to update these forward-looking statements.<br />
    3. 3. Our session’s Chatter feed<br />
    4. 4. Agenda<br />The evolution of JavaScript<br />Tools to help you test:<br />Jasmine by Pivotal Labs<br /> YUI Test by Yahoo!<br />Demos. How to use these tools with the force.com platform<br />Questions & Answers <br />
    5. 5. Session Objective<br />By the end of this session you will be ready to get started with Jasmine and YUI Test inside your force.com environment.<br />
    6. 6. It’s not the ‘90s anymore<br />In the past only trivial tasks were delegated to JavaScript<br />Today’s applications have a growing dependency on JavaScript and asynchronous services <br />
    7. 7. It’s not the ‘90s anymore<br />
    8. 8. JavaScript is no longer a toy language<br />
    9. 9. JavaScript is no longer a toy language<br />
    10. 10. We’ve come a long way…<br />
    11. 11. JavaScript breaks!<br />
    12. 12. We have tools now<br />Jasmine test framework by Pivotal Labs<br />YUI test framework by Yahoo<br />
    13. 13. Jasmine<br />Jasmine is a behavior-driven development framework for testing your JavaScript code. <br />It does not depend on any other JavaScript frameworks. <br />It has a clean, obvious syntax so that you can easily write tests.<br />
    14. 14. What is BDD?<br />Behavior Driven Development<br />“BDD is a second-generation, outside-in, pull-based, multiple-stakeholder, multiple-scale, high-automation, agile methodology.”<br />Huh?<br />
    15. 15. Hold on what is BDD?<br />“A practice of writing test cases in a natural language that non-programmers can read.”<br />
    16. 16. Example<br />function helloWorld() {<br /> return "Hello, World!";<br />}<br />describe('helloWorld()', function() {<br />it('says hello', function() {<br />expect(helloWorld()).toEqual("Hello, World!");<br /> });<br />});<br />
    17. 17. Another Example<br />function copyToDiv() {<br />var source = document.getElementById(‘source’);<br />var content = document.getElementById(‘content’);<br />content.innerHTML = source.innerHTML;<br />}<br />describe(’copyToDiv()', function() {<br />it(’copies input data to content', function() {<br />copyToDiv();<br />var content = document.getElementById(‘content’).innerHTML<br />expect(content).toEqual(‘source data’);<br /> });<br />});<br />
    18. 18. Tests are called “Specs”<br /><ul><li>You tell Jasmine about a spec with a call to it() with a description string and the function.
    19. 19. The string is a description of a behavior that you want your production code to exhibit; it should be meaningful to you when reading a report.</li></ul>it('should increment a variable', function () { <br />varfoo = 0; <br />foo++; <br />});<br />
    20. 20. Expectations<br />Within your spec you will express expectations about the behavior of your application code. This is done using the expect() function.<br />function increment(foo) {<br /> returnfoo++;<br />}<br />describe('increment()', function() {<br /> it('should increment a variable', function() {<br />varfoo = 0; <br />expect(increment(foo)).toEqual(1);<br /> });<br />});<br />
    21. 21. Suites<br />Specs are grouped in Suites. Suites are defined using the global describe() function.<br />describe('Calculator', function () { <br />it('can add a number', function() {<br /> ... <br /> }); <br />it(’multiply some numbers', function() {<br /> ... <br /> }); <br />});<br />
    22. 22. Expectation Matchers<br />Jasmine has several built-in matchers. For example:<br />expect(x).toEqual(y); <br />expect(x).toBeNull(); <br />expect(x).toContain(y); <br />expect(x).toBeLessThan(y); <br />expect(x).toBeGreaterThan(y); <br />expect(fn).toThrow(e); <br />Each matcher’s criteria can be inverted by prepending .not<br />
    23. 23. Custom Matchers<br />Jasmine includes a small set of matchers that cover many common situations. <br />However you can write custom matchers when you want to assert a more specific sort of expectation. <br />Custom matchers help to document the intent of your specs, and can help to remove code duplication in your specs.<br />
    24. 24. Custom Matchers – An Example<br />To add the matcher to your suite, call this.addMatchers() from within a <br />beforeEach or block. <br />beforeEach(function() { <br />this.addMatchers({ <br />toBeVisible: function() {return this.actual.isVisible();}<br /> }); <br />}); <br />
    25. 25. Custom Matchers<br />beforeEach(function() {<br />this.addMatchers({<br />toBeACar: function() {<br /> return this.actual.hasWheels() && this.actual.hasEngine() && this.actual.hasSteeringWheel();<br /> }<br /> });<br />});<br />describe(‘car’, function() {<br />it(‘is a car’, function() {<br />expect(car).toBeACar();<br /> });<br />});<br />
    26. 26. beforeEach<br />A suite can have a beforeEach() declaration. It takes a function that is run before each spec. For example:<br />describe('some suite', function () { <br />varsuiteWideFoo; <br />beforeEach(function () { <br />suiteWideFoo = 1; <br /> }); <br />it('should equal bar', function () { <br /> expect(suiteWideFoo).toEqual(1);<br /> }); <br />}); <br />
    27. 27. beforeEach<br />Runner beforeEach() functions are executed before every spec in all suites, and execute BEFORE suite beforeEach() functions. For example:<br />varrunnerWideFoo = []; <br />beforeEach(function () { <br />runnerWideFoo.push('runner');<br /> });<br />describe('some suite', function () {<br />beforeEach(function () { <br />runnerWideFoo.push('suite');<br /> }); <br />it('should equal bar', function () { <br />expect(runnerWideFoo).toEqual(['runner', 'suite']); <br /> }); <br />}); <br />
    28. 28. afterEach<br />Similarly, there is an afterEach() declaration. It takes a function that is run after each spec. For example:<br />describe('some suite', function () { <br />varsuiteWideFoo = 1; <br />afterEach(function () { <br />suiteWideFoo = 0; <br /> }); <br />it('should equal 1', function() {<br /> expect(suiteWideFoo).toEqual(1);<br /> }); <br />it('should equal 0 after', function(){ <br /> expect (suiteWideFoo).toEqual(0); <br /> };<br />}); <br />
    29. 29. afterEach<br />varrunnerWideFoo = [];<br />afterEach(function () {<br />runnerWideFoo.push('runner');<br />});<br />describe('some suite', function () {<br />afterEach(function () {<br />runnerWideFoo.push('suite');<br /> });<br />it('should be empty', function () {<br />expect(runnerWideFoo).toEqual([]);<br /> });<br />it('should be populated after', function () {<br />expect(runnerWideFoo).toEqual(['suite', 'runner']);<br /> };<br />});<br />
    30. 30. Spies!<br />Spies allow you to “spy” on the function being called granting far more visibility into its behavior then can be achieved by inspecting the return value.<br />
    31. 31. How to spy on your code<br />function Hostess(name) {<br />this.name = name;<br />this.getName = function() { return name; };<br />this.greetParty = function() {<br /> return “My name is “ + this.getName() + “ please follow me”<br /> };<br />//..<br />it(‘uses the name’, function() {<br />var hostess = new Hostess(‘Janet’); <br />spyOn(hostess, ‘getName’);<br />expect(hostess.greetParty()).toMatch(‘My name is Janet please follow me’);<br />expect(hostess.getName).toHaveBeenCalled();<br />});<br />
    32. 32. Spy-Specific Matchers<br />There are spy-specific matchers that are very handy.<br />expect(x).toHaveBeenCalled()<br />expect(x).toHaveBeenCalledWith(arguments)<br />expect(x).not.toHaveBeenCalled()<br />expect(x).not.toHaveBeenCalledWith(arguments)<br />
    33. 33. Useful Properties<br />Spies have some useful properties:<br />callCount<br />mostRecentCall.args<br />argsForCall[i]<br />Spies are automatically removed after each spec. They may be set in the beforeEach function.<br />
    34. 34. Spy Example 2<br />varKlass = function () { }; <br />Klass.staticMethod = function (arg) { <br /> return arg; <br />}; <br />Klass.prototype.method = function (arg) { <br /> return arg; <br />};<br />Klass.prototype.methodWithCallback = function (callback) { <br /> return callback('foo'); <br />};<br />
    35. 35. Spy Example 2 Continued…<br />it('should spy on a static method of Klass', <br />function() { <br />spyOn(Klass, 'staticMethod'); <br />Klass.staticMethod('foo argument'); <br />expect(Klass.staticMethod).toHaveBeenCalledWith('foo argument'); <br />}); <br />
    36. 36. Spy Example 2 Continued…<br />it('should spy on an instance method of a Klass', function() { <br />varobj = new Klass(); <br />spyOn(obj, 'method'); <br />obj.method('foo argument'); <br />expect(obj.method).toHaveBeenCalledWith('foo argument'); <br />var obj2 = new Klass(); <br /> spyOn(obj2, 'method'); <br /> expect(obj2.method).not.toHaveBeenCalled(); <br /> });<br />
    37. 37. Spy Example 2 Continued…<br />it('should spy on Klass.methodWithCallback', function() { <br />var callback = jasmine.createSpy(); <br /> new Klass().methodWithCallback(callback);<br />expect(callback).toHaveBeenCalledWith('foo');<br />});<br />
    38. 38. Spy Example 3<br />varKlass = function () { }; <br />varKlass.prototype.asyncMethod = function (callback) { <br />someAsyncCall(callback); <br />};<br />
    39. 39. Spy Example 3 Continued…<br />it('should test async call') {<br />spyOn(Klass, 'asyncMethod');<br />var callback = jasmine.createSpy();<br />Klass.asyncMethod(callback);<br />expect(callback).not.toHaveBeenCalled();<br />varsomeResponseData = 'foo';<br /> Klass.asyncMethod.mostRecentCall.args[0](someResponseData);<br />expect(callback).toHaveBeenCalledWith(someResponseData);<br />});<br />
    40. 40. Asynchronous Specs<br />Imagine you need to make a call that is asynchronous - an AJAX API, event callback, or some other JavaScript library. <br />That is, the call returns immediately, yet you want to make expectations ‘at some point in the future’ after some magic happens in the background.<br />Jasmine allows you to do this with runs(), waits() and waitsFor() blocks.<br />
    41. 41. Asynchronous Specs<br />describe('Spreadsheet', function() { <br />it('should calculate the total asynchronously', function () { <br />var spreadsheet = new Spreadsheet(); spreadsheet.fillWith(lotsOfFixureDataValues()); spreadsheet.asynchronouslyCalculateTotal(); waitsFor(function() { return spreadsheet.calculationIsComplete(); }, "Spreadsheet calculation never completed", 10000); <br />runs(function () { <br /> expect(spreadsheet.total).toEqual(123456);<br /> }); <br />});<br />}); <br />
    42. 42. Jasmine Demo<br />
    43. 43. Alexis Williams<br />salesforce.com<br />
    44. 44. YUI Test – What is it?<br />YUI Test is a test driven development framework for testing your JavaScript code. <br />It does not depend on any other JavaScript frameworks. <br />It allows you to plug into any other frameworks: Dojo, jQuery, Prototype…<br />It has a clean JSON like syntax many of us are familiar with already<br />
    45. 45. YUI Test – What are the Benefits?<br />Reduces overall ramp up time<br />Familiar JSON like syntax<br />Tests cases are easy to create<br />Provides setup and tear down functionality<br />Writing tests (unit) is easy<br />Explicitly indicates test outcomes<br />Groups together test case statistics<br />
    46. 46. Getting Started with YUI Test<br />Create HTML page<br />Include required resources: Java script and CSS<br />Create test case<br />Add unit tests<br />Add test cases to test suite<br />Open in web browser to run test suite and view results<br />
    47. 47. Test Cases and Unit Tests {Test Methods}<br />Test Case is comprised of unit tests<br />Unit tests exercise small, isolated units of code<br />Unit tests have expected input and outputs<br />The test case will present the number of passed and failed unit tests<br />
    48. 48. Creating a Test Case and Test Methods Pt. 1<br />Create a new instance of the TestCase<br />Any method prefixed with lower case test is considered a unit test to run<br />Any method not defined already or prefixed with test is considered a helper method<br />Built in methods:<br />Set up: set up data that will be consumed in test methods<br />Tear down: construct to tear down data setup for test methods<br />
    49. 49. Creating a Test Case and Test Methods Pt. 2<br />
    50. 50. Test Method Assertions Pt. 1<br />Equality Assertions<br />areEqual() and areNotEqual(): both accept 3 arguments: expected value, actual value, and optional failure message<br />Assert.areEqual(5, 5); //passes<br />Assert.areEqual(5, "5"); //passes<br />Assert.areEqual(5, 6, "Five was expected."); //fails<br />Sameness Assertions<br />areSame() and areNotSame(): same argument structure like equals, but uses different comparison operator (===)<br />Assert.areSame(5, "5"); //fails<br />Assert.areNotSame(5, 6); //passes<br />Assert.areSame(5, 6, "Five was expected."); //fails<br />
    51. 51. Test Method Assertions Pt. 2<br />Data Type Assertions<br />test the data type of variables: accepts 2 arguments, the variable to test, and an optional error message. <br />Assert.isString("Hello world"); //passes<br />Assert.isNumber(1); //passes<br />Assert.isArray([]); //passes<br />Assert.isObject([]); //passes<br />Assert.isFunction(function(){}); //passes<br />Assert.isBoolean(true); //passes<br />Assert.isObject(function(){}); //passes<br />
    52. 52. Test Method Assertions Pt. 3<br />Special Value Assertions<br />designed to test for the following special values: true, false, NaN, null, and undefined. Accepts 2 arguments again: the variable to test, and an optional error message.<br />Assert.isFalse(false); //passes <br />Assert.isNaN(5 / "5"); //passes<br />Assert.isNull(null); //passes<br />Assert.isUndefined(undefined); //passes<br />Forced Failures<br />Forced failure you can optionally pass a message into<br />
    53. 53. Getting Test Cases Ready to Run Pt. 1<br />Create new instance of TestSuite<br />Add testCases to TestSuite<br />Create new instance of TestLogger<br />Add the test suite to TestLogger<br />Run the test suite with TestRunner when the DOM is ready<br />
    54. 54. Getting Test Cases Ready to Run Pt. 2<br />
    55. 55. Enter The Complexities – Browser Environment<br />Dependencies upon page events<br />Execution types:<br />Synchronous<br />Asynchronous<br />Different behaviors exhibited per browser<br />
    56. 56. Simulating User Actions {Mouse & Keyboard}<br />Each event is fired by a corresponding method on UserAction that accepts two arguments: the target of the event and an optional object specifying additional information for the event<br />YAHOO.util.UserAction object provides methods to simulate basic user events involving the keyboard and mouse<br />
    57. 57. Simulating Mouse Actions<br />Seven mouse events that can be simulated: click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemove<br />var element = document.getElementById("myDiv");<br />//simulate a click Alt key down<br />YAHOO.util.UserAction.click(element, { altKey: true});<br />//simulate a double click with Ctrl key down<br />YAHOO.util.UserAction.dblclick(element, { ctrlKey: true });<br />
    58. 58. Simulating Keyboard Actions<br />Three key events that can be simulated: keyup, keydown, keypress<br />Key events also support the ctrlKey, altKey, shiftKey, and metaKey event properties<br />var element = document.getElementById("myDiv");<br />//simulate a keydown on the A key<br />YAHOO.util.UserAction.keydown(element, { keyCode: 97 });<br />//simulate a keyup on the A key<br />YAHOO.util.UserAction.keyup(element, { keyCode: 97 });<br />
    59. 59. Asynchronous Testing – Wait Pt. 1<br />YUI Test allows you to pause a currently running test and resume either after a set amount of time or at another designated time<br />The TestCase object has a method called wait(). When wait() is called, the test immediately exits (meaning that any code after that point will be ignored) and waits for a signal to resume the test.<br />
    60. 60. Asynchronous Testing – Wait Pt. 2<br />A test may be resumed after a certain amount of time by passing in two arguments to wait(): a function to execute and the number of milliseconds to wait before executing the function (similar to using setTimeout()). <br />The function passed in as the first argument will be executed as part of the current test (in the same scope) after the specified amount of time.<br />
    61. 61. Asynchronous Testing – Wait Pt. 3<br /> Example of using wait with a timer<br />
    62. 62. Real Life Example {Ghost Text} Pt. 1<br />Need: when user loads a VF page they are presented ghost text (grey) in description field. The text should disappear when they click in the field, text color should be black, and reappear if they don’t add any text with text color back to grey<br />Translation: create function to populate text and erase text<br />Function: <br />Add ghost text to field<br />Remove ghost text from field<br />Add ghost text to field if needed<br />
    63. 63. Real Life Example {Ghost Text} Pt. 2<br />Render ghost text when Description field is null<br />
    64. 64. Real Life Example {Ghost Text} Pt. 3<br />Remove ghost text when clicking in Description field<br />
    65. 65. Real Life Example {Ghost Text} Pt. 4<br />
    66. 66. Working with the Results Test Logger<br />Use the test logger to output the results<br />varoLogger = new YAHOO.tool.TestLogger();<br />YAHOO.tool.TestRunner.run();<br />
    67. 67. Working with the Results Test Reporter Pt. 1<br />Use the test reporter to create a form that posts the results to a specific URL: <br />results - the serialized results object.<br />useragent - the user-agent string of the browser.<br />timestamp - the date and time that the report was sent.<br />One way direction – no return processed from server<br />Does not cause you to navigate away from page<br />varoReporter = new YAHOO.tool.TestReporter("http://www.yourserver.com/path/to/target");<br />oReporter.report(results);<br />
    68. 68. Working with the Results Test Reporter Pt. 2<br />Custom fields<br />Custom fields can be added to the results report using the addField() method<br />Custom fields are appended to the standard fields posted<br />oReporter.addField("User_Story_c", "a0lB00000004IkV");<br />oReporter.addField("Test_Case__c", "a07B0000000DlSEIA0");<br />
    69. 69. Working with the Results Test Reporter Pt. 3<br />Two serialization formats for the results objects: XML and JSON<br />XML is the default format<br />varoReporter = new YAHOO.tool.TestReporter("https://na1.salesforce.com/apex/processYIUTest", YAHOO.tool.TestFormat.JSON);<br />
    70. 70. Which one should I use?<br />
    71. 71. ResourcesJasmine: http://pivotal.github.com/jasmine/YUI Test: http://developer.yahoo.com/yui/yuitest/<br />
    72. 72. Questions?<br />
    73. 73. How Could Dreamforce Be Better? Tell Us!<br />Log in to the Dreamforce app to submit<br />surveys for the sessions you attended<br />Use the Dreamforce Mobile app to submit surveys<br />OR<br />Every session survey you submit is a chance to win an iPod nano!<br />

    ×