72
JavaScript Is Not a Toy It’s Time it was Tested Developers James Hatton : salesforce.com Alexis Williams: salesforce.com

Java Script Isn\'t a Toy Anymore

Embed Size (px)

DESCRIPTION

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

Citation preview

Page 1: Java Script Isn\'t a Toy Anymore

JavaScript Is Not a ToyIt’s Time it was Tested

Developers

James Hatton : salesforce.comAlexis Williams: salesforce.com

Page 2: Java Script Isn\'t a Toy Anymore

Safe HarborSafe 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.

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.

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.

Page 3: Java Script Isn\'t a Toy Anymore

Our session’s Chatter feed

Page 4: Java Script Isn\'t a Toy Anymore

Agenda

The evolution of JavaScript

Tools to help you test:– Jasmine by Pivotal Labs

– YUI Test by Yahoo!

Demos. How to use these tools with the force.com

platform

Questions & Answers

Page 5: Java Script Isn\'t a Toy Anymore

Session Objective

By the end of this session you will be ready to get

started with Jasmine and YUI Test inside your

force.com environment.

Page 6: Java Script Isn\'t a Toy Anymore

It’s not the ‘90s anymore

In the past only trivial tasks were delegated to

JavaScript

Today’s applications have a growing dependency on

JavaScript and asynchronous services

Page 7: Java Script Isn\'t a Toy Anymore

It’s not the ‘90s anymore

Page 8: Java Script Isn\'t a Toy Anymore

JavaScript is no longer a toy language

Page 9: Java Script Isn\'t a Toy Anymore

JavaScript is no longer a toy language

Page 10: Java Script Isn\'t a Toy Anymore

We’ve come a long way…

Page 11: Java Script Isn\'t a Toy Anymore

JavaScript breaks!

Page 12: Java Script Isn\'t a Toy Anymore

We have tools now

Jasmine test framework by Pivotal Labs

YUI test framework by Yahoo

Page 13: Java Script Isn\'t a Toy Anymore

Jasmine

Jasmine is a behavior-driven development framework

for testing your JavaScript code.

It does not depend on any other JavaScript

frameworks.

It has a clean, obvious syntax so that you can easily

write tests.

Page 14: Java Script Isn\'t a Toy Anymore

What is BDD?

Behavior Driven Development

“BDD is a second-generation, outside-in, pull-based,

multiple-stakeholder, multiple-scale, high-automation,

agile methodology.”

Huh?

Page 15: Java Script Isn\'t a Toy Anymore

Hold on what is BDD?

“A practice of writing test cases in a

natural language that non-

programmers can read.”

Page 16: Java Script Isn\'t a Toy Anymore

Example

function helloWorld() {

return "Hello, World!";

}

describe('helloWorld()', function() {

it('says hello', function() {

expect(helloWorld()).toEqual("Hello, World!");

});

});

Page 17: Java Script Isn\'t a Toy Anymore

Another Example

function copyToDiv() {

var source = document.getElementById(‘source’);

var content = document.getElementById(‘content’);

content.innerHTML = source.innerHTML;

}

describe(’copyToDiv()', function() {

it(’copies input data to content', function() {

copyToDiv();

var content = document.getElementById(‘content’).innerHTML

expect(content).toEqual(‘source data’);

});

});

Page 18: Java Script Isn\'t a Toy Anymore

Tests are called “Specs”

it('should increment a variable', function () {

var foo = 0;

foo++;

});

You tell Jasmine about a spec with a call to it() with a

description string and the function.

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.

Page 19: Java Script Isn\'t a Toy Anymore

Expectations Within your spec you will express expectations about the behavior of your

application code. This is done using the expect() function.

function increment(foo) {

return foo++;

}

describe('increment()', function() {

it('should increment a variable', function() {

var foo = 0;

expect(increment(foo)).toEqual(1);

});

});

Page 20: Java Script Isn\'t a Toy Anymore

Suites

Specs are grouped in Suites. Suites are defined using

the global describe() function.

describe('Calculator', function () {

it('can add a number', function() {

...

});

it(’multiply some numbers', function() {

...

});

});

Page 21: Java Script Isn\'t a Toy Anymore

Expectation Matchers

Jasmine has several built-in matchers. For example:

expect(x).toEqual(y);

expect(x).toBeNull();

expect(x).toContain(y);

expect(x).toBeLessThan(y);

expect(x).toBeGreaterThan(y);

expect(fn).toThrow(e);

Each matcher’s criteria can be inverted by prepending .not

Page 22: Java Script Isn\'t a Toy Anymore

Custom Matchers

Jasmine includes a small set of matchers that cover

many common situations.

However you can write custom matchers when you

want to assert a more specific sort of expectation.

Custom matchers help to document the intent of your

specs, and can help to remove code duplication in your

specs.

Page 23: Java Script Isn\'t a Toy Anymore

Custom Matchers – An Example

To add the matcher to your suite, call this.addMatchers() from within a beforeEach or block.

beforeEach(function() { this.addMatchers({ toBeVisible: function() {return this.actual.isVisible();} });

});

Page 24: Java Script Isn\'t a Toy Anymore

Custom Matchers

beforeEach(function() { this.addMatchers({ toBeACar: function() { return this.actual.hasWheels() &&

this.actual.hasEngine() && this.actual.hasSteeringWheel(); } });});

describe(‘car’, function() { it(‘is a car’, function() {

expect(car).toBeACar(); });});

Page 25: Java Script Isn\'t a Toy Anymore

beforeEach

A suite can have a beforeEach() declaration. It takes a

function that is run before each spec. For example:

describe('some suite', function () { var suiteWideFoo;

beforeEach(function () { suiteWideFoo = 1; });

it('should equal bar', function () { expect(suiteWideFoo).toEqual(1); }); });

Page 26: Java Script Isn\'t a Toy Anymore

beforeEach Runner beforeEach() functions are executed before every spec in

all suites, and execute BEFORE suite beforeEach() functions. For

example:

var runnerWideFoo = []; beforeEach(function () { runnerWideFoo.push('runner'); });

describe('some suite', function () { beforeEach(function () { runnerWideFoo.push('suite'); });

it('should equal bar', function () { expect(runnerWideFoo).toEqual(['runner', 'suite']); }); });

Page 27: Java Script Isn\'t a Toy Anymore

afterEach Similarly, there is an afterEach() declaration. It takes a

function that is run after each spec. For example:

describe('some suite', function () { var suiteWideFoo = 1; afterEach(function () { suiteWideFoo = 0; });

it('should equal 1', function() { expect(suiteWideFoo).toEqual(1); });

it('should equal 0 after', function(){ expect (suiteWideFoo).toEqual(0); };});

Page 28: Java Script Isn\'t a Toy Anymore

afterEach

var runnerWideFoo = [];

afterEach(function () { runnerWideFoo.push('runner');});

describe('some suite', function () { afterEach(function () { runnerWideFoo.push('suite'); }); it('should be empty', function () { expect(runnerWideFoo).toEqual([]); }); it('should be populated after', function () { expect(runnerWideFoo).toEqual(['suite', 'runner']); };});

Page 29: Java Script Isn\'t a Toy Anymore

Spies!

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.

Page 30: Java Script Isn\'t a Toy Anymore

How to spy on your codefunction Hostess(name) { this.name = name; this.getName = function() { return name; }; this.greetParty = function() { return “My name is “ + this.getName() + “ please follow me” };

//.. it(‘uses the name’, function() { var hostess = new Hostess(‘Janet’); spyOn(hostess, ‘getName’); expect(hostess.greetParty()).toMatch(‘My name is Janet please follow me’); expect(hostess.getName).toHaveBeenCalled();});

Page 31: Java Script Isn\'t a Toy Anymore

Spy-Specific Matchers

There are spy-specific matchers that are very handy.

expect(x).toHaveBeenCalled()

expect(x).toHaveBeenCalledWith(arguments)

expect(x).not.toHaveBeenCalled()

expect(x).not.toHaveBeenCalledWith(arguments)

Page 32: Java Script Isn\'t a Toy Anymore

Useful Properties

Spies have some useful properties:

callCount

mostRecentCall.args

argsForCall[i]

Spies are automatically removed after each spec. They

may be set in the beforeEach function.

Page 33: Java Script Isn\'t a Toy Anymore

Spy Example 2

var Klass = function () { };

Klass.staticMethod = function (arg) { return arg;

};

Klass.prototype.method = function (arg) { return arg;

};

Klass.prototype.methodWithCallback = function (callback) {

return callback('foo'); };

Page 34: Java Script Isn\'t a Toy Anymore

Spy Example 2 Continued…

it('should spy on a static method of Klass',

function() { spyOn(Klass, 'staticMethod'); Klass.staticMethod('foo argument'); expect(Klass.staticMethod).toHaveBeenCalledWith('foo

argument');

});

Page 35: Java Script Isn\'t a Toy Anymore

Spy Example 2 Continued…

it('should spy on an instance method of a Klass', function() {

var obj = new Klass(); spyOn(obj, 'method'); obj.method('foo argument'); expect(obj.method).toHaveBeenCalledWith('foo argument');

var obj2 = new Klass(); spyOn(obj2, 'method'); expect(obj2.method).not.toHaveBeenCalled();

});

Page 36: Java Script Isn\'t a Toy Anymore

Spy Example 2 Continued…

it('should spy on Klass.methodWithCallback', function() {

var callback = jasmine.createSpy(); new Klass().methodWithCallback(callback); expect(callback).toHaveBeenCalledWith('foo');

});

Page 37: Java Script Isn\'t a Toy Anymore

Spy Example 3

var Klass = function () { };

var Klass.prototype.asyncMethod = function (callback) { someAsyncCall(callback); };

Page 38: Java Script Isn\'t a Toy Anymore

Spy Example 3 Continued…

it('should test async call') { spyOn(Klass, 'asyncMethod'); var callback = jasmine.createSpy();

Klass.asyncMethod(callback); expect(callback).not.toHaveBeenCalled();

var someResponseData = 'foo'; Klass.asyncMethod.mostRecentCall.args[0](someResponseData); expect(callback).toHaveBeenCalledWith(someResponseData);

});

Page 39: Java Script Isn\'t a Toy Anymore

Asynchronous Specs

Imagine you need to make a call that is asynchronous -

an AJAX API, event callback, or some other

JavaScript library.

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.

Jasmine allows you to do this with runs(), waits() and

waitsFor() blocks.

Page 40: Java Script Isn\'t a Toy Anymore

Asynchronous Specs

describe('Spreadsheet', function() {

it('should calculate the total asynchronously', function () {

var spreadsheet = new Spreadsheet(); spreadsheet.fillWith(lotsOfFixureDataValues()); spreadsheet.asynchronouslyCalculateTotal(); waitsFor(function() { return spreadsheet.calculationIsComplete(); }, "Spreadsheet calculation never completed", 10000);

runs(function () { expect(spreadsheet.total).toEqual(123456); });

});

});

Page 41: Java Script Isn\'t a Toy Anymore

Jasmine Demo

Page 42: Java Script Isn\'t a Toy Anymore

Alexis Williams

salesforce.com

Page 43: Java Script Isn\'t a Toy Anymore

YUI Test – What is it?

YUI Test is a test driven development framework for testing

your JavaScript code.

It does not depend on any other JavaScript frameworks.

It allows you to plug into any other frameworks: Dojo, jQuery,

Prototype…

It has a clean JSON like syntax many of us are familiar with

already

Page 44: Java Script Isn\'t a Toy Anymore

YUI Test – What are the Benefits?

Reduces overall ramp up time

Familiar JSON like syntax

Tests cases are easy to create

Provides setup and tear down functionality

Writing tests (unit) is easy

Explicitly indicates test outcomes

Groups together test case statistics

Page 45: Java Script Isn\'t a Toy Anymore

Getting Started with YUI Test

Create HTML page

Include required resources: Java script and CSS

Create test case

Add unit tests

Add test cases to test suite

Open in web browser to run test suite and view results

Page 46: Java Script Isn\'t a Toy Anymore

Test Cases and Unit Tests {Test Methods}

Test Case is comprised of unit tests

Unit tests exercise small, isolated units of code

Unit tests have expected input and outputs

The test case will present the number of passed and

failed unit tests

Page 47: Java Script Isn\'t a Toy Anymore

Creating a Test Case and Test Methods Pt. 1

Create a new instance of the TestCase

Any method prefixed with lower case test is considered

a unit test to run

Any method not defined already or prefixed with test is

considered a helper method

Built in methods:– Set up: set up data that will be consumed in test methods

– Tear down: construct to tear down data setup for test methods

Page 48: Java Script Isn\'t a Toy Anymore

Creating a Test Case and Test Methods Pt. 2

Page 49: Java Script Isn\'t a Toy Anymore

Test Method Assertions Pt. 1

Equality Assertions– areEqual() and areNotEqual(): both accept 3 arguments:

expected value, actual value, and optional failure message• Assert.areEqual(5, 5); //passes

• Assert.areEqual(5, "5"); //passes

• Assert.areEqual(5, 6, "Five was expected."); //fails

Sameness Assertions– areSame() and areNotSame(): same argument structure like

equals, but uses different comparison operator (===)• Assert.areSame(5, "5"); //fails

• Assert.areNotSame(5, 6); //passes

• Assert.areSame(5, 6, "Five was expected."); //fails

Page 50: Java Script Isn\'t a Toy Anymore

Test Method Assertions Pt. 2

Data Type Assertions– test the data type of variables: accepts 2 arguments, the

variable to test, and an optional error message. • Assert.isString("Hello world"); //passes

• Assert.isNumber(1); //passes

• Assert.isArray([]); //passes

• Assert.isObject([]); //passes

• Assert.isFunction(function(){}); //passes

• Assert.isBoolean(true); //passes

• Assert.isObject(function(){}); //passes

Page 51: Java Script Isn\'t a Toy Anymore

Test Method Assertions Pt. 3

Special Value Assertions– 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.• Assert.isFalse(false); //passes

• Assert.isNaN(5 / "5"); //passes

• Assert.isNull(null); //passes

• Assert.isUndefined(undefined); //passes

Forced Failures– Forced failure you can optionally pass a message into

Page 52: Java Script Isn\'t a Toy Anymore

Getting Test Cases Ready to Run Pt. 1

Create new instance of TestSuite

Add testCases to TestSuite

Create new instance of TestLogger

Add the test suite to TestLogger

Run the test suite with TestRunner when the DOM is

ready

Page 53: Java Script Isn\'t a Toy Anymore

Getting Test Cases Ready to Run Pt. 2

Page 54: Java Script Isn\'t a Toy Anymore

Enter The Complexities – Browser Environment

Dependencies upon page events

Execution types:– Synchronous

– Asynchronous

Different behaviors exhibited per browser

Page 55: Java Script Isn\'t a Toy Anymore

Simulating User Actions {Mouse & Keyboard}

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

YAHOO.util.UserAction object provides methods to

simulate basic user events involving the keyboard and

mouse

Page 56: Java Script Isn\'t a Toy Anymore

Simulating Mouse Actions

Seven mouse events that can be simulated: click,

dblclick, mousedown, mouseup, mouseover, mouseout,

mousemove

var element = document.getElementById("myDiv");

//simulate a click Alt key downYAHOO.util.UserAction.click(element, { altKey: true});

//simulate a double click with Ctrl key downYAHOO.util.UserAction.dblclick(element, { ctrlKey: true });

Page 57: Java Script Isn\'t a Toy Anymore

Simulating Keyboard Actions

Three key events that can be simulated: keyup,

keydown, keypress

Key events also support the ctrlKey, altKey, shiftKey,

and metaKey event properties

var element = document.getElementById("myDiv");

//simulate a keydown on the A keyYAHOO.util.UserAction.keydown(element, { keyCode: 97 });

//simulate a keyup on the A keyYAHOO.util.UserAction.keyup(element, { keyCode: 97 });

Page 58: Java Script Isn\'t a Toy Anymore

Asynchronous Testing – Wait Pt. 1

YUI Test allows you to pause a currently running test

and resume either after a set amount of time or at

another designated time

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.

Page 59: Java Script Isn\'t a Toy Anymore

Asynchronous Testing – Wait Pt. 2

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()).

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.

Page 60: Java Script Isn\'t a Toy Anymore

Asynchronous Testing – Wait Pt. 3

Example of using wait with a timer

Page 61: Java Script Isn\'t a Toy Anymore

Real Life Example {Ghost Text} Pt. 1

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

Translation: create function to populate text and erase

text

Function: – Add ghost text to field

– Remove ghost text from field

– Add ghost text to field if needed

Page 62: Java Script Isn\'t a Toy Anymore

Real Life Example {Ghost Text} Pt. 2

Render ghost text when Description field is null

Page 63: Java Script Isn\'t a Toy Anymore

Real Life Example {Ghost Text} Pt. 3

Remove ghost text when clicking in Description field

Page 64: Java Script Isn\'t a Toy Anymore

Real Life Example {Ghost Text} Pt. 4

Page 65: Java Script Isn\'t a Toy Anymore

Working with the Results Test Logger

Use the test logger to output the results

var oLogger = new YAHOO.tool.TestLogger();YAHOO.tool.TestRunner.run();

Page 66: Java Script Isn\'t a Toy Anymore

Working with the Results Test Reporter Pt. 1

Use the test reporter to create a form that posts the

results to a specific URL: – results - the serialized results object.

– useragent - the user-agent string of the browser.

– timestamp - the date and time that the report was sent.

– One way direction – no return processed from server

– Does not cause you to navigate away from page

var oReporter = new YAHOO.tool.TestReporter("http://www.yourserver.com/path/to/target");oReporter.report(results);

Page 67: Java Script Isn\'t a Toy Anymore

Working with the Results Test Reporter Pt. 2

Custom fields– Custom fields can be added to the results report using the

addField() method

– Custom fields are appended to the standard fields posted

oReporter.addField("User_Story_c", "a0lB00000004IkV");oReporter.addField("Test_Case__c", "a07B0000000DlSEIA0");

Page 68: Java Script Isn\'t a Toy Anymore

Working with the Results Test Reporter Pt. 3

Two serialization formats for the results objects: XML

and JSON

XML is the default format

var oReporter = new YAHOO.tool.TestReporter("https://na1.salesforce.com/apex/processYIUTest", YAHOO.tool.TestFormat.JSON);

Page 69: Java Script Isn\'t a Toy Anymore

Which one should I use?

JASMINE YUI Test

Standalone Framework (no 3rd party dependencies)

✔ ✔

Behavioral Driven Development ✔ ✖

Similarity with Apex tests ✖ ✔

Browser Compatibility ✖ ✖

Automation with CI ✖ (ruby for now) ✔ (requires custom script/plugin)

Supports Asynchronous Tests ✔ ✔

Spying & Faking Behaviors ✔ ✖

Page 70: Java Script Isn\'t a Toy Anymore

Resources

Jasmine: http://pivotal.github.com/jasmine/YUI Test: http://developer.yahoo.com/yui/yuitest/

Page 71: Java Script Isn\'t a Toy Anymore

Questions?

Page 72: Java Script Isn\'t a Toy Anymore

How Could Dreamforce Be Better? Tell Us!

Log in to the Dreamforce app to submit

surveys for the sessions you attendedUse the

Dreamforce Mobile app to submit

surveysEvery session survey you submit is

a chance to win an iPod nano!

OR