With the right tools, you too can create a substantial responsive mobile application with no Apex required. Join us to learn how Visualforce Remote Objects creates a foundation for access to your backend data supplemented. Popular Javascript frameworks like AngularJS and Ionic bring structure and responsive mobile user experience. Deliver mobile enterprise solutions with the tools you already know.
Action functions in Visualforce allow JavaScript functions to call Apex controller methods using an asynchronous AJAX request. An action function is defined using <apex:actionFunction> and specifies the Apex method to call. The JavaScript function can then invoke the action function to execute the controller method. Action support adds AJAX functionality to a component and calls a controller method based on events, while action functions can be directly called from JavaScript. The example demonstrates using an action function from a checkbox onclick and action support from an input field to call different controller methods and update an output text.
This document compares Visualforce ActionFunction and RemoteAction for building single-page applications on the Force.com platform. It demonstrates using each approach to build a simple "This vs That" battle app. ActionFunction exposes Apex methods to JavaScript but only supports string parameters, while RemoteAction allows flexible parameter passing but requires more JavaScript code. The document also shows integrating a single-page app with jQuery, Bootstrap, Backbone and other JavaScript libraries using RemoteAction.
Test Coverage for Your WP REST API ProjectPantheon
The document discusses the importance of test coverage for WordPress REST API projects. It explains that test coverage ensures security and reliability by explicitly testing that private information is not disclosed, unauthorized requests are not permitted, and consistent responses are returned. The document provides examples of unit and integration tests for a phone number formatting function and REST API endpoint. It emphasizes that test-driven development and continuous integration helps catch errors and security issues early.
This document summarizes a Salesforce developer session on leveraging StandardSetController in Apex and Visualforce to build a custom "Add to Campaigns" application. It discusses using StandardSetController with list view filters to retrieve campaign records, and an Apex controller extension to integrate this with a Visualforce page. It allows users to select multiple campaigns to add a contact or lead to using checkboxes, while leveraging existing platform functionality and custom settings for customization. Code samples demonstrate the controller, wrappers, and custom setting used.
The document provides instructions for migrating user and group security between Salesforce organizations using the Force.com Migration Tool. It describes how to set up the tool, including installing required software, configuring connection settings, constructing a project manifest file to specify metadata to migrate, retrieving metadata from the source org, and deploying it to the target org. The tool uses Ant tasks to automate migrating metadata and security configurations between orgs.
[Test bash manchester] contract testing in practicePierre Vincent
End-to-end integration plays a strong part in testability, unfortunately when an application grows, these kind of tests become a burden: brittleness, slower feedback and overall poor return on investment to improve quality.
Contract testing brings an alternative approach for validating integration points in fast-changing distributed systems. Because contracts don’t need integration environments, they can give very fast feedback to prevent API and messaging breaking changes from being introduced early-on.
Contracts are also a catalyst for inter-team communications. They help interactions between services become a central attribute in designing solutions, as opposed to an emergency concern when they break at a late integration stage.
This workshop covers the core concepts of contracts testing and contracts can play a part in reducing the struggles of integration tests. The attendees will be working on practical examples of defining contracts between teams and services, as well as implement them using the Pact tool-chain.
Highly efficient Visualforce pages have rock-solid HTML, CSS, and JavaScript. They do not support a single pixel-perfect UI across all browsers and instead allow for differences. They are also stateless, do not poll servers excessively, and defer difficult work asynchronously using techniques like the transient keyword, Visualforce remoting, streaming API, and the @future annotation.
This document discusses Salesforce S-Controls, which are lightweight web applications hosted by Salesforce and executed in the browser. It provides examples of when to use S-Controls to enhance the user interface, automate processes, and customize the Salesforce experience. AJAX and the SforceClient toolkit are introduced as technologies that can be used to build dynamic and asynchronous S-Controls.
This document contains an agenda and overview for a presentation on Salesforce S-Controls. S-Controls allow for lightweight web applications hosted on Salesforce that can enhance the user interface and automate processes using JavaScript and AJAX. The document discusses when to use S-Controls, provides examples, and reviews the AJAX toolkit and SforceClient methods for building S-Controls.
This document provides information about an advanced developer workshop including login details, speakers, and an agenda. It discusses core Salesforce platform services, demonstrates a sample data model and requirements for a warehouse application, and introduces Apex, triggers, Visualforce, testing, and other developer topics. The document also includes several code snippets and links to additional learning resources.
How We Built the Private AppExchange App (Apex, Visualforce, RWD)Salesforce Developers
The AppExchange and Success Community team built a brand new app this year: the Private AppExchange. Join us and learn how the team built this managed package, the choices we made and why. We will talk about the AppExchange Search Framework that all three of these products are built upon and we will talk about how we made a responsive UI that works on whatever device you choose.
If you are familiar with object-oriented languages like Java or C#, Apex may be the language you already almost know. Apex is the cloud-based programming language used on the Salesforce1 Platform to take your enterprise applications to the next level. In this webinar, get an introduction to how Apex is similar to other languages, how you can start coding in Apex with just a web browser, and an overview of the many functions Apex can perform for your applications and users.
Key Takeaways
Programmers familiar with object-oriented languages will be able to learn Apex easily
Apex can perform a wide range of functions from serving as a controller for Visualforce pages to scheduled tasks in the background.
Join us to explore the Wave Platform, including APIs, data loading, packaging, and licensing. We will discuss using Wave with Force.com, including Visualforce, Lightning, Apex, REST, and more.
This document provides a summary of a presentation about connecting clouds with Force.com. It discusses various integration patterns for connecting Force.com with other cloud platforms, including inbound, outbound, and hybrid patterns. It also discusses Force.com toolkits and provides a demo of integrating Force.com with Microsoft Azure, Google App Engine, Amazon AWS, and Heroku. Best practices for each integration option are also highlighted.
This document provides an overview and introduction to Apex for developers. It begins with an introduction to Apex and the Salesforce platform. It then outlines the agenda which includes an overview of the platform, writing Apex classes, accessing data using SOQL and DML, writing triggers, and additional topics like Visualforce, REST APIs, and unit testing. It encourages participants to use their developer environment and provides a link to sign up. It describes what will be built in the session which is an app to manage sessions and speakers at a conference. It includes two forward-looking statements disclaimers.
Speed is one of the most important features of the lightning experience. One of the first considerations when building your application or component using Lightning should be to make it fast and responsive. Join us in this session to learn about the speed of lightning. We will walk through the process of building a lightning component, instrumenting it using Lightning Metrics Service, analyzing the performance and optimizing your application for a lightning fast experience!
Talk given by Marat Vyshegorodtsev and Sergey Gorbaty. Enterprise Security team at Salesforce, in January 2017.
Discusses a set of open source tools that analyze the Apex/VisualForce code and advise on its quality.
A mini framework for event handling on the OpportunityContactRole (OCR) and AccountContactRole (ACR) objects. Using a custom (dynamic) Visualforce page driven by a controller extension, you can replace the standard related lists
1) The Salesforce1 Platform allows developers to build apps using core services like Chatter, Analytics, and APIs.
2) Developers can use declarative tools like workflows, visualforce, and formula fields or program with Apex.
3) Apex is Salesforce's programming language that allows developers to extend functionality with custom objects, logic, and integrations using HTTP callouts.
Description:
Whether you are an experienced developer coming to Apex from another language, or an intermediate level Apex developer, this webinar will take you to the next level in programming on the Salesforce and Force.com platform. We will dive deeper into Apex, and guide you through examples of advanced design patterns and techniques, and much more related to Apex on the Salesforce1 platform!
Key Takeaways:
::Programmers familiar with object-oriented languages will be able to learn Apex easily
::Apex can perform a wide range of functions from serving as a controller for Visualforce pages to scheduled tasks in the background.
::Get a deep dive into testing and code coverage on Force.com, and learn some solid best practices and recipes for writing better tests.
Intended Audience:
::Programmers familiar with object-oriented languages, and looking for an deeper dive into Apex
This document summarizes a presentation about integrating Force.com with Heroku. It discusses calling web services from Force.com applications both synchronously and asynchronously. It also covers calling Force.com APIs from external applications using REST and OAuth authentication. Finally, it introduces a new Heroku Postgres feature called Data Clips that allows retrieving SQL query results in different formats, and how to integrate these clips into Force.com applications.
New to Force.com and needing a quick orientation to bring you up to speed? Join us for this series of brief introductory sessions on Force.com, the world’s leading cloud platform that lets you build apps rapidly using configuration-driven development and powerful programmatic logic.
Each Friday one of our experts will walk you through one of the core elements of the Force.com platform and cover the basics you need to build your first app in the cloud. Each session is 30 minutes long.
Introduction to Developing Android Apps With the Salesforce Mobile SDKSalesforce Developers
This session will show mobile developers how to build enterprise Android applications using our new Salesforce Mobile SDK. Not only will users be shown how to use the new features and functions of the SDK but we'll also dive into best practices for building mobile APIs focussed on enterprise business applications.
This slide deck is from the Advanced Apex webinar I presented for Salesforce.com which can be viewed at https://developer.salesforce.com/events/webinars/advanced_apex.
This document provides an overview of Lightning Web Components Episode 2 which focuses on working with Salesforce data. It discusses how the Lightning Data Service and UI API are used to retrieve and display Salesforce record data. It also demonstrates how to use wire services to connect Lightning Web Components to Apex methods to retrieve and manipulate data. The document concludes with instructions for configuring Lightning Web Components to be used in the Lightning App Builder.
The Spring '14 Release is chock-full of great updates for developers, such as the ability to perform DML operations in JavaScript and tons of API updates. Watch this webinar to discover new and upcoming Salesforce1 Platform features slated for this release including:
Visualforce Updates: Visualforce enhancements in Spring ’14 include Visualforce Remote Objects for performing DML operations in JavaScript without the need for an Apex Controller, historical trending capabilities with the Analytics API, support for report chart components, PageReference URI support anchors, and several new components.
Force.com Canvas: Force.com Canvas continues to add useful features like the ability to access a Canvas app in the Chatter Publisher and Feed, the ability to add a Canvas app to the Salesforce1 App Mobile Navigation, support for using events between a Canvas app and a Visualforce page, as well as a new debugging console.
API Updates: New features have been added to SOQL, SOSL, REST API, SOAP API, Bulk API, Metadata API and the Streaming API. Additionally, we have opened up the ability to use the Data.com APIs, and added a new Place Order API to integrate Salesforce order data into any web or mobile application.
Developer Console: New features have been added that let you search through all files for specific snippets in your organization, change look and feel settings on your console, along with several user-experience additions like context menus.
Apex Code: Spring ‘14 adds new classes, methods and interfaces. You can now access reports in Apex with the Analytics API and updates have been made to Chatter in Apex.
This document discusses Salesforce S-Controls, which are lightweight web applications hosted by Salesforce and executed in the browser. It provides examples of when to use S-Controls to enhance the user interface, automate processes, and customize the Salesforce experience. AJAX and the SforceClient toolkit are introduced as technologies that can be used to build dynamic and asynchronous S-Controls.
This document contains an agenda and overview for a presentation on Salesforce S-Controls. S-Controls allow for lightweight web applications hosted on Salesforce that can enhance the user interface and automate processes using JavaScript and AJAX. The document discusses when to use S-Controls, provides examples, and reviews the AJAX toolkit and SforceClient methods for building S-Controls.
This document provides information about an advanced developer workshop including login details, speakers, and an agenda. It discusses core Salesforce platform services, demonstrates a sample data model and requirements for a warehouse application, and introduces Apex, triggers, Visualforce, testing, and other developer topics. The document also includes several code snippets and links to additional learning resources.
How We Built the Private AppExchange App (Apex, Visualforce, RWD)Salesforce Developers
The AppExchange and Success Community team built a brand new app this year: the Private AppExchange. Join us and learn how the team built this managed package, the choices we made and why. We will talk about the AppExchange Search Framework that all three of these products are built upon and we will talk about how we made a responsive UI that works on whatever device you choose.
If you are familiar with object-oriented languages like Java or C#, Apex may be the language you already almost know. Apex is the cloud-based programming language used on the Salesforce1 Platform to take your enterprise applications to the next level. In this webinar, get an introduction to how Apex is similar to other languages, how you can start coding in Apex with just a web browser, and an overview of the many functions Apex can perform for your applications and users.
Key Takeaways
Programmers familiar with object-oriented languages will be able to learn Apex easily
Apex can perform a wide range of functions from serving as a controller for Visualforce pages to scheduled tasks in the background.
Join us to explore the Wave Platform, including APIs, data loading, packaging, and licensing. We will discuss using Wave with Force.com, including Visualforce, Lightning, Apex, REST, and more.
This document provides a summary of a presentation about connecting clouds with Force.com. It discusses various integration patterns for connecting Force.com with other cloud platforms, including inbound, outbound, and hybrid patterns. It also discusses Force.com toolkits and provides a demo of integrating Force.com with Microsoft Azure, Google App Engine, Amazon AWS, and Heroku. Best practices for each integration option are also highlighted.
This document provides an overview and introduction to Apex for developers. It begins with an introduction to Apex and the Salesforce platform. It then outlines the agenda which includes an overview of the platform, writing Apex classes, accessing data using SOQL and DML, writing triggers, and additional topics like Visualforce, REST APIs, and unit testing. It encourages participants to use their developer environment and provides a link to sign up. It describes what will be built in the session which is an app to manage sessions and speakers at a conference. It includes two forward-looking statements disclaimers.
Speed is one of the most important features of the lightning experience. One of the first considerations when building your application or component using Lightning should be to make it fast and responsive. Join us in this session to learn about the speed of lightning. We will walk through the process of building a lightning component, instrumenting it using Lightning Metrics Service, analyzing the performance and optimizing your application for a lightning fast experience!
Talk given by Marat Vyshegorodtsev and Sergey Gorbaty. Enterprise Security team at Salesforce, in January 2017.
Discusses a set of open source tools that analyze the Apex/VisualForce code and advise on its quality.
A mini framework for event handling on the OpportunityContactRole (OCR) and AccountContactRole (ACR) objects. Using a custom (dynamic) Visualforce page driven by a controller extension, you can replace the standard related lists
1) The Salesforce1 Platform allows developers to build apps using core services like Chatter, Analytics, and APIs.
2) Developers can use declarative tools like workflows, visualforce, and formula fields or program with Apex.
3) Apex is Salesforce's programming language that allows developers to extend functionality with custom objects, logic, and integrations using HTTP callouts.
Description:
Whether you are an experienced developer coming to Apex from another language, or an intermediate level Apex developer, this webinar will take you to the next level in programming on the Salesforce and Force.com platform. We will dive deeper into Apex, and guide you through examples of advanced design patterns and techniques, and much more related to Apex on the Salesforce1 platform!
Key Takeaways:
::Programmers familiar with object-oriented languages will be able to learn Apex easily
::Apex can perform a wide range of functions from serving as a controller for Visualforce pages to scheduled tasks in the background.
::Get a deep dive into testing and code coverage on Force.com, and learn some solid best practices and recipes for writing better tests.
Intended Audience:
::Programmers familiar with object-oriented languages, and looking for an deeper dive into Apex
This document summarizes a presentation about integrating Force.com with Heroku. It discusses calling web services from Force.com applications both synchronously and asynchronously. It also covers calling Force.com APIs from external applications using REST and OAuth authentication. Finally, it introduces a new Heroku Postgres feature called Data Clips that allows retrieving SQL query results in different formats, and how to integrate these clips into Force.com applications.
New to Force.com and needing a quick orientation to bring you up to speed? Join us for this series of brief introductory sessions on Force.com, the world’s leading cloud platform that lets you build apps rapidly using configuration-driven development and powerful programmatic logic.
Each Friday one of our experts will walk you through one of the core elements of the Force.com platform and cover the basics you need to build your first app in the cloud. Each session is 30 minutes long.
Introduction to Developing Android Apps With the Salesforce Mobile SDKSalesforce Developers
This session will show mobile developers how to build enterprise Android applications using our new Salesforce Mobile SDK. Not only will users be shown how to use the new features and functions of the SDK but we'll also dive into best practices for building mobile APIs focussed on enterprise business applications.
This slide deck is from the Advanced Apex webinar I presented for Salesforce.com which can be viewed at https://developer.salesforce.com/events/webinars/advanced_apex.
This document provides an overview of Lightning Web Components Episode 2 which focuses on working with Salesforce data. It discusses how the Lightning Data Service and UI API are used to retrieve and display Salesforce record data. It also demonstrates how to use wire services to connect Lightning Web Components to Apex methods to retrieve and manipulate data. The document concludes with instructions for configuring Lightning Web Components to be used in the Lightning App Builder.
The Spring '14 Release is chock-full of great updates for developers, such as the ability to perform DML operations in JavaScript and tons of API updates. Watch this webinar to discover new and upcoming Salesforce1 Platform features slated for this release including:
Visualforce Updates: Visualforce enhancements in Spring ’14 include Visualforce Remote Objects for performing DML operations in JavaScript without the need for an Apex Controller, historical trending capabilities with the Analytics API, support for report chart components, PageReference URI support anchors, and several new components.
Force.com Canvas: Force.com Canvas continues to add useful features like the ability to access a Canvas app in the Chatter Publisher and Feed, the ability to add a Canvas app to the Salesforce1 App Mobile Navigation, support for using events between a Canvas app and a Visualforce page, as well as a new debugging console.
API Updates: New features have been added to SOQL, SOSL, REST API, SOAP API, Bulk API, Metadata API and the Streaming API. Additionally, we have opened up the ability to use the Data.com APIs, and added a new Place Order API to integrate Salesforce order data into any web or mobile application.
Developer Console: New features have been added that let you search through all files for specific snippets in your organization, change look and feel settings on your console, along with several user-experience additions like context menus.
Apex Code: Spring ‘14 adds new classes, methods and interfaces. You can now access reports in Apex with the Analytics API and updates have been made to Chatter in Apex.
1. JavaScript Is Not a ToyIt’s Time it was TestedDevelopersJames Hatton : salesforce.comAlexis Williams: salesforce.com
2. 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.
4. AgendaThe evolution of JavaScriptTools to help you test:Jasmine by Pivotal Labs YUI Test by Yahoo!Demos. How to use these tools with the force.com platformQuestions & Answers
5. Session ObjectiveBy the end of this session you will be ready to get started with Jasmine and YUI Test inside your force.com environment.
6. It’s not the ‘90s anymoreIn the past only trivial tasks were delegated to JavaScriptToday’s applications have a growing dependency on JavaScript and asynchronous services
12. We have tools nowJasmine test framework by Pivotal LabsYUI test framework by Yahoo
13. JasmineJasmine 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.
14. What is BDD?Behavior Driven Development“BDD is a second-generation, outside-in, pull-based, multiple-stakeholder, multiple-scale, high-automation, agile methodology.”Huh?
15. Hold on what is BDD?“A practice of writing test cases in a natural language that non-programmers can read.”
17. Another Examplefunction 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’).innerHTMLexpect(content).toEqual(‘source data’); });});
18. Tests are called “Specs”You tell Jasmine about a spec with a call to it() with a description string and the function.
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.it('should increment a variable', function () { varfoo = 0; foo++; });
20. ExpectationsWithin your spec you will express expectations about the behavior of your application code. This is done using the expect() function.function increment(foo) { returnfoo++;}describe('increment()', function() { it('should increment a variable', function() {varfoo = 0; expect(increment(foo)).toEqual(1); });});
21. SuitesSpecs 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() { ... }); });
22. Expectation MatchersJasmine 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
23. Custom MatchersJasmine 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.
24. Custom Matchers – An ExampleTo 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();} }); });
26. beforeEachA suite can have a beforeEach() declaration. It takes a function that is run before each spec. For example:describe('some suite', function () { varsuiteWideFoo; beforeEach(function () { suiteWideFoo = 1; }); it('should equal bar', function () { expect(suiteWideFoo).toEqual(1); }); });
27. beforeEachRunner beforeEach() functions are executed before every spec in all suites, and execute BEFORE suite beforeEach() functions. For example:varrunnerWideFoo = []; beforeEach(function () { runnerWideFoo.push('runner'); });describe('some suite', function () {beforeEach(function () { runnerWideFoo.push('suite'); }); it('should equal bar', function () { expect(runnerWideFoo).toEqual(['runner', 'suite']); }); });
28. afterEachSimilarly, there is an afterEach() declaration. It takes a function that is run after each spec. For example:describe('some suite', function () { varsuiteWideFoo = 1; afterEach(function () { suiteWideFoo = 0; }); it('should equal 1', function() { expect(suiteWideFoo).toEqual(1); }); it('should equal 0 after', function(){ expect (suiteWideFoo).toEqual(0); };});
29. afterEachvarrunnerWideFoo = [];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']); };});
30. 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.
31. 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();});
32. Spy-Specific MatchersThere are spy-specific matchers that are very handy.expect(x).toHaveBeenCalled()expect(x).toHaveBeenCalledWith(arguments)expect(x).not.toHaveBeenCalled()expect(x).not.toHaveBeenCalledWith(arguments)
33. Useful PropertiesSpies have some useful properties:callCountmostRecentCall.argsargsForCall[i]Spies are automatically removed after each spec. They may be set in the beforeEach function.
34. Spy Example 2varKlass = function () { }; Klass.staticMethod = function (arg) { return arg; }; Klass.prototype.method = function (arg) { return arg; };Klass.prototype.methodWithCallback = function (callback) { return callback('foo'); };
35. 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'); });
36. Spy Example 2 Continued…it('should spy on an instance method of a Klass', function() { varobj = 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(); });
37. Spy Example 2 Continued…it('should spy on Klass.methodWithCallback', function() { var callback = jasmine.createSpy(); new Klass().methodWithCallback(callback);expect(callback).toHaveBeenCalledWith('foo');});
38. Spy Example 3varKlass = function () { }; varKlass.prototype.asyncMethod = function (callback) { someAsyncCall(callback); };
39. Spy Example 3 Continued…it('should test async call') {spyOn(Klass, 'asyncMethod');var callback = jasmine.createSpy();Klass.asyncMethod(callback);expect(callback).not.toHaveBeenCalled();varsomeResponseData = 'foo'; Klass.asyncMethod.mostRecentCall.args[0](someResponseData);expect(callback).toHaveBeenCalledWith(someResponseData);});
40. Asynchronous SpecsImagine 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.
41. Asynchronous Specsdescribe('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); }); });});
44. 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
45. YUI Test – What are the Benefits?Reduces overall ramp up timeFamiliar JSON like syntaxTests cases are easy to createProvides setup and tear down functionalityWriting tests (unit) is easyExplicitly indicates test outcomesGroups together test case statistics
46. Getting Started with YUI TestCreate HTML pageInclude required resources: Java script and CSSCreate test caseAdd unit testsAdd test cases to test suiteOpen in web browser to run test suite and view results
47. Test Cases and Unit Tests {Test Methods}Test Case is comprised of unit testsUnit tests exercise small, isolated units of codeUnit tests have expected input and outputsThe test case will present the number of passed and failed unit tests
48. Creating a Test Case and Test Methods Pt. 1Create a new instance of the TestCaseAny method prefixed with lower case test is considered a unit test to runAny method not defined already or prefixed with test is considered a helper methodBuilt in methods:Set up: set up data that will be consumed in test methodsTear down: construct to tear down data setup for test methods
50. Test Method Assertions Pt. 1Equality AssertionsareEqual() and areNotEqual(): both accept 3 arguments: expected value, actual value, and optional failure messageAssert.areEqual(5, 5); //passesAssert.areEqual(5, "5"); //passesAssert.areEqual(5, 6, "Five was expected."); //failsSameness AssertionsareSame() and areNotSame(): same argument structure like equals, but uses different comparison operator (===)Assert.areSame(5, "5"); //failsAssert.areNotSame(5, 6); //passesAssert.areSame(5, 6, "Five was expected."); //fails
51. Test Method Assertions Pt. 2Data Type Assertionstest the data type of variables: accepts 2 arguments, the variable to test, and an optional error message. Assert.isString("Hello world"); //passesAssert.isNumber(1); //passesAssert.isArray([]); //passesAssert.isObject([]); //passesAssert.isFunction(function(){}); //passesAssert.isBoolean(true); //passesAssert.isObject(function(){}); //passes
52. Test Method Assertions Pt. 3Special Value Assertionsdesigned 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"); //passesAssert.isNull(null); //passesAssert.isUndefined(undefined); //passesForced FailuresForced failure you can optionally pass a message into
53. Getting Test Cases Ready to Run Pt. 1Create new instance of TestSuiteAdd testCases to TestSuiteCreate new instance of TestLoggerAdd the test suite to TestLoggerRun the test suite with TestRunner when the DOM is ready
55. Enter The Complexities – Browser EnvironmentDependencies upon page eventsExecution types:SynchronousAsynchronousDifferent behaviors exhibited per browser
56. 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 eventYAHOO.util.UserAction object provides methods to simulate basic user events involving the keyboard and mouse
57. Simulating Mouse ActionsSeven mouse events that can be simulated: click, dblclick, mousedown, mouseup, mouseover, mouseout, mousemovevar 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 });
58. Simulating Keyboard ActionsThree key events that can be simulated: keyup, keydown, keypressKey events also support the ctrlKey, altKey, shiftKey, and metaKey event propertiesvar 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 });
59. Asynchronous Testing – Wait Pt. 1YUI Test allows you to pause a currently running test and resume either after a set amount of time or at another designated timeThe 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.
60. Asynchronous Testing – Wait Pt. 2A 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.
62. Real Life Example {Ghost Text} Pt. 1Need: 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 greyTranslation: create function to populate text and erase textFunction: Add ghost text to fieldRemove ghost text from fieldAdd ghost text to field if needed
63. Real Life Example {Ghost Text} Pt. 2Render ghost text when Description field is null
64. Real Life Example {Ghost Text} Pt. 3Remove ghost text when clicking in Description field
66. Working with the Results Test LoggerUse the test logger to output the resultsvaroLogger = new YAHOO.tool.TestLogger();YAHOO.tool.TestRunner.run();
67. Working with the Results Test Reporter Pt. 1Use 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 serverDoes not cause you to navigate away from pagevaroReporter = new YAHOO.tool.TestReporter("http://www.yourserver.com/path/to/target");oReporter.report(results);
68. Working with the Results Test Reporter Pt. 2Custom fieldsCustom fields can be added to the results report using the addField() methodCustom fields are appended to the standard fields postedoReporter.addField("User_Story_c", "a0lB00000004IkV");oReporter.addField("Test_Case__c", "a07B0000000DlSEIA0");
69. Working with the Results Test Reporter Pt. 3Two serialization formats for the results objects: XML and JSONXML is the default formatvaroReporter = new YAHOO.tool.TestReporter("https://na1.salesforce.com/apex/processYIUTest", YAHOO.tool.TestFormat.JSON);
73. How Could Dreamforce Be Better? Tell Us!Log in to the Dreamforce app to submitsurveys for the sessions you attendedUse the Dreamforce Mobile app to submit surveysOREvery session survey you submit is a chance to win an iPod nano!
Editor's Notes
#22: 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
#32: 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
#33: 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.
#39: 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
#41: 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.
#52: 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.
#55: Some of the benefits of YUI testSome things you still need to deal with…
#56: Nice thing is standardized way to mimic user inputs that works everywhere
#65: Update your tests to run correctly in each browserYAHOO.env.ua.{browser}YAHOO.env.ua.gecko
#67: I like the approach because we can save the data into a custom object for reporting purposes
#68: Obvious benefits include creating new test executions relating user story record to test case