How to Create Google Chrome Apps and Extensions from your Ext JS App

Introduction

How to Create Google Chrome Apps and Extensions from your Ext JS AppGoogle Chrome is an important delivery mechanism for web content. As of September 2014, Chrome has a 59.6% browser market share.

It’s not just the browser; it’s also Chrome OS, the operating system that runs on Chromebooks. According to Gartner, 5.2 million units are expected to be sold this year. The demand for Chromebooks is rising, particularly in the US education market.

Google Chrome is an important delivery mechanism for web content. As of September 2014, Chrome has a 59.6% browser market share.
Source: w3schools.com, 2014

The Google Chrome Web Store is a great place to get exposure for your applications because everyone who uses the Google Chrome browser can install these apps.

Ext JS helps you build powerful web applications. Just like web apps, Chrome apps are written in JavaScript, CSS and HTML, so Ext JS is the right framework for creating great looking and performing Chrome apps.

There are different types of installable Chrome apps: extensions, packaged apps and hosted apps.

  • Hosted web apps are regular web applications, served from a web server.
  • Packaged web apps are bundled and are completely installed in Chrome browser with access to special Chrome APIs
  • Extensions are small apps that can modify and enhance the functionality of Chrome browser.

Today we will examine how to build a hosted app in detail; the process of creating a packaged Chrome app or extension is much different and may be covered in future posts. If you are interested in building packaged apps or Chrome extensions, please see the following resources that have been created by the Sencha team:

Let’s take a look at the steps you’ll need to follow to package your Ext JS app for Google Chrome.

Requirements:

  • Ext JS 5 and Sencha Cmd
  • An Ext JS application originally generated with Sencha Cmd
  • A Google account, which will be used as a developer account to access your apps
  • One icon for the Google Chrome Web Store (128×128 pixel PNG)
  • Artwork, which will be used to feature the app in the Web Store:
    • 440×280 PNG used as a tile in the search results
    • At least one 1280×800 PNG screenshot of the app
  • Access to a web server (hosted apps require a network connection; load the application from a whitelisted url).

For demo purposes, I’ve created a simple Ext JS 5 todo application. The namespace of my app is called: ExtTodo. This application was originally generated with Sencha Cmd 5.

I’m sharing this example in my GitHub repository.

Here are the steps:

1. Disable the image slicer

By default, the build process enables the image slicer to create fallback images for legacy browsers. Google Chrome is a modern browser, so we don’t need fallback images. Therefore, we’ll disable the slicer to reduce the build time and minimize our production output.

Open ~/exttodo/.sencha/app/sencha.cfg and then add the following under the namespace:

# Skip the image slice process
skip.slice=1

2. Build with Sencha Cmd

After disabling the image slicer, let’s create a production build. Run this command from the application folder:

sencha app build production

The build process creates a single, compressed .js file containing everything needed to run your application. It contains all Sencha Ext JS classes that are used as well as all of your own custom application code. The build process will also create a minified stylesheet for production, which contains the framework theme and maybe custom styling.

3. Verify your build

With your file explorer, browse to the build/production/MyApp folder, to locate the exttodo application (e.g. ~/exttodo/build/production/ExtTodo).

Notice the following file structure:

  • app.js – the single minified JS file
  • app.json – contains app specific settings
  • index.html – landing page for our application
  • resources/ – folder that contains all of the configured images, fonts and other resources for our application
  • ExtTodo-all.css – the CSS theme

4. Upload the build to your webserver

Now, it’s time to upload your build to a web server.

Note: If you don’t have a web server and just want to test how to create a Google Chrome app with Ext JS and Sencha Cmd, you can skip this step. Later, in the manifest file, link to the build/production/MyApp folder on localhost.

5. Create a new empty folder

Create the googlechromeapp folder:

~/exttodo/googlechromeapp/ExtTodo

This folder will contain Chrome Webstore assets and a manifest file.

6. Copy the icon and artwork into the root of the googlechromeapp/MyApp folder

7. Create a manifest file

It’s actually very easy to create hosted Google Chrome apps. All you need is a manifest.json file, which you put in the root of the ~/exttodo/googlechromeapp/MyApp folder. It looks like the following:

{
        "name": "ExtTodo",
        "description": "A simple Ext JS 5 Todo app",
        "version": "0.1",
        "manifest_version": 2,
        "app": {
                "urls": [
                        "http://localhost/exttodo/build/production/ExtTodo"
                ],
                "launch": {
                        "web_url":  "http://localhost/exttodo/build/production/ExtTodo"
                }
        },
        "icons": {
                "128": "icon_128.png"
        }
}

Note: In this example, I am setting the app url to localhost, just for testing purposes. As soon as I am hosting my web application online, I can set it to http://mydomain.com/mychromeapp/

Let’s review each of the important properties in this JSON configuration object:

  • nameRequired. The name of the application; this is displayed in the store and in Chrome’s launcher.
  • descriptionRecommended. A brief description of the app.
  • versionRequired. The version of this metadata; each time you update the metadata this number must be incremented.
  • manifest_versionRequired. The current supported manifest version is 2.
  • appRequired. The remote URLs that the app uses.
    • urlsRecommended. Array with the URLs for the pages in the hosted app.
    • launchRequired. Specifies what happens when the user launches the app.
      • web_urlRequired. Specifies the launch page as an absolute URL.
  • iconsRecommended. Specifies the icon shown in the launcher.
  • For a complete overview see, the Google Developer Guide on Installable Web Apps.

8. Create a zip file

Now, create a zip file from the contents of ~/exttodo/googlechromeapp/MyApp. the manifest.json and the icon, those files should be the root of your zip file.

Now, create a zip file from the contents of ~/exttodo/googlechromeapp/MyApp. the manifest.json and the icon, those files should be the root of your zip file.

9. Upload the file to the Google Dashboard

Open the Google dashboard (you need to be logged in to Google).

Click the Add new item button, and accept the Google web store agreement.

Upload the file to the Google Dashboard

Next, click the Choose file button, and select the ~/exttodo/googlechromeapp/MyApp/myapp.zip file. This action
will upload the package.

After uploading, it will forward you to the set up publish screen, where you can write a detailed app store description and showcase app screenshots, etc. We don’t need to do this for our tutorial.

Click Save draft and return to dashboard button.

Note:If you want to publish the web app or want to sell applications through the app store, then there are some additional steps. See the last steps in this guide, Publishing Your App.

Basically, you will need to fill out the publish settings. Publishing apps requires a one-time registration fee of $5, to make sure developers upload serious web applications.

If your hosted app is listed in the Chrome Web Store, you must prove that you control each domain specified in this field.

10. Test it

To test your application running as a Chrome App, go to the Chrome settings. See the screenshot below.

Test it

Open the Extensions tab.

Check the Developer Mode checkbox, and click the Pack extension button.

The pop-up window below will be shown. For the Extension root directory, select ~/exttodo/googlechromeapp/MyApp folder. Then click the Pack extension button.

The pop-up window below will be shown. For the Extension root directory, select ~/exttodo/googlechromeapp/MyApp folder. Then click the Pack extension button.

The pop-up window below will be shown. For the Extension root directory, select ~/exttodo/googlechromeapp/MyApp folder. Then click the Pack extension button.

This will download two files. MyApp.pem and MyApp.crx. MyApp.pem is a file with a secure key. You need to save this file, outside the googlechromeapp/MyApp/ folder.

Pack Extension

I moved the MyApp.crx, which is the app launch file, into the ~/exttodo/googlechromeApp/MyApp/ folder.

After that, press the Load unpacked extension button.

In the next popup window, select the ~/exttodo/googlechromeapp/MyApp folder. Then, the app icon will show up in the extensions list.

To test the hosted application, open a new tab in Google Chrome, and select the apps button (or type the following url: chrome://apps). The 128×128 app icon will be visible and this will launch my extodo app.

Conclusion

Google Chrome is an app platform worth looking at because many people are using Google Chrome as their favorite browser. Ext JS 5 helps you build powerful applications, and because Chrome apps are web applications we can use this platform to get exposure. There are different types of Chrome apps you can build, such as packaged (offline) Chrome Apps, Chrome browser extensions (to enhance browser functionality) and hosted web applications. In this tutorial, I’ve demonstrated how developers can create hosted Chrome applications in a few easy steps.

What kind of Chrome Apps are you building? Let me know in the comments section below.

chrome-apps-teaser.png No Comments   Read more

Ext JS 5 Tablet Support

Guest Blog Post

Ext JS 5 Tablet SupportExt JS has been recognized as the leading framework for desktop web applications. The landscape of computer usage, both personal and enterprise, has been changing dramatically since tablets started challenging PC sales worldwide. Sencha recognized this shift and launched new features and optimizations in Ext JS 5.

Ext JS 5 learned a bunch of new tricks from Sencha Touch 2. Years of experience gathered with the best mobile web application framework made its desktop counterpart ready for an impeccable presentation on modern tablets. We can see those updates across the board — in the class system, event management, widgets, and even the new deployment options.

Ext JS 4 vs Ext JS 5 for Devices
In addition to presenting rich web applications on tablets, Ext JS 5 fully supports all interaction patterns tailored for touchscreen devices

Class System

The cornerstone of the new capabilities for tablets comes in the latest Class System updates. While Ext JS 4 introduced the config system, it wasn’t exactly enforced until Sencha Touch 2. Developers can now get the most out of the config object, getters, setters, updaters, appliers, and even the mighty Ext.factory in Ext JS 5.

Mind you, the new Ext JS config system doesn’t require use of the config object, which follows the requirements of version 4. However, it is capable of translating properties of config object into their root counterparts, automagically.

To better explain this concept, observe the following Ext JS code snippet:

Ext JS code snippet

Normally, the html property should come outside of the config block, at least in Ext JS. Because Ext.Component has a member function called setHtml, the class system feeds the value to the setter.

This important practice helped Ext JS 5 reuse the code written for Sencha Touch 2 and vice versa. It’s not just that it allows developers to share code among applications written in the two frameworks, it also enabled Sencha to incorporate many important features from Sencha Touch in Ext JS 5.

Events

Touch is the central input method for touchscreens, which is why Sencha bundled touch event and gesture support in Ext JS 5. The key player in this upgrade is the new event normalization pattern that translates common events into the variants relative to the platform.

Ext JS mousedown code snippet

In this particular example, the mousedown event will be used as intended on most desktop clients. However, the event management system will automatically identify touchscreen devices and switch to touchstart or pointerdown, based on browser support. Event translation is essential for proper interaction with tablets.

Event updates are bi-directional, adding new features to both mobile and desktop applications. Ext JS widgets now react on swipe, longpress, and other gestures otherwise designed for mobile applications, even when executed in a desktop browser. Naturally, the events that require multiple touches (e.g. pinch, rotate) can’t be ported to a mouse-operated desktop environment. Of course, it was not the intention to encourage developers to port a mobile experience over to desktops, but to ensure consistency in presentation.

With touch events enabled, momentum scrolling made its way to the framework as well. The Touch Scroller is now an integral part of Ext JS 5, enabled automatically on touchscreen devices. No configuration necessary.

Both Class System and event management updates added a significant boost to tablet support. End users will experience these features by interacting with views and widgets. Let’s see how widgets are laid out for optimum tablet support.

Widgets

The quest for optimal touchscreen presentation goes beyond enabling touch events. Certain mouse-based interaction patterns (e.g. mouseover/hover, right click) will not work on tablets. Widgets that support those events on desktop browsers now employ alternative means of interface manipulation.

Grid panel is the perfect example of such a widget. If we observe header menus, we will quickly notice that it takes a number of interactions to turn them on.

Ext JS Mousedown code snippet
Expanded grid header menu

First, to activate the menu, we mouse over the column header. Then the UI shows an arrow button aligned to the right. Finally, we press the button to pull down the menu.

This particular workflow is impossible to replicate on touchscreens, as is. Nonetheless, the grid panel is touchscreen-aware and capable of replacing the native desktop pattern native with a touchscreen alternative. When viewed on a tablet device, grids will show header menus on longpress event, requiring a user to simply tap on a column header a bit longer than usual.

Another interesting example is row highlighting. It’s interesting because there are now alternatives for it on tablets. The main purpose of highlighting is easier recognition of a mouse pointer placement. Because touchscreens don’t have that problem, row highlighting becomes obsolete.

Widgets in Ext JS 5 are not only optimized for presentation on tablets, they also include new features from Sencha Touch 2. For example, icon-enabled buttons make user interfaces even more beautiful.

The iconCls property now works in Ext JS 5 as well. Because buttons are baked into other widgets such as TabPanels, we see that the whole stack has been updated.

Ext JS Mousedown code snippet
The new TabPanel with icon support

The new Sencha Charts package is yet another example of how beautifully these two frameworks interact with one another. Charts prove that the new class system and event management updates make user interfaces truly device agnostic, while maintaining persistent API and performance. Definitely give Charts a try, whether you develop in Ext JS 5 or Sencha Touch 2.

Sencha Charts is the first package shared between Ext JS 5 and Sencha Touch 2
Sencha Charts is the first package shared between Ext JS 5 and Sencha Touch 2 (complete).

In addition to these specific updates, any widget can have mobile-specific design rules with the introduction of the responsive configuration plugin. Any configuration property that has a setter can be updated based on orientation, or even more carefully planned viewport dimension rules. Phil Guerrant wrote a detailed blog post on Designing Responsive Applications with Ext JS, and you can also see the feature in this demo application.

If there’s one takeaway from this section, it’s that Ext JS 5 provides developers with enough tools to make widgets device agnostic. When developing for mouseover or right click, have touchscreens in mind and plan for alternative event listeners. The framework offers a number of solutions with built-in widgets. Observe, learn, and reuse them to build successful apps.

Finally, a perfectly crafted tablet application should find its way to a user’s device.

Deployment

After you finish all the hard work of crafting the perfect desktop and tablet application, the time comes for deployment. Luckily more than one option is available:

  1. Browser. The simplest and the most straightforward solution is to deliver a web application through HTTP(S) protocol to a client’s browser. Don’t forget to use the Sencha Cmd ‘sencha app build production’ command to minify, compress, and optimize the source code.
  2. Sencha Space. Enterprise applications require enterprise solutions. Space helps deliver and manage secure web applications in a BYOD environment, and works flawlessly with Ext JS 5 applications.
  3. Cordova. Hybrid application developers will welcome the improvements in integration between Ext JS 5 and Sencha Cmd 5. The new building capabilities allow developers to easily wrap apps for Cordova (or PhoneGap) with a simple “sencha app build native” command.

Conclusion

Ext JS 5 doesn’t just make applications viewable on tablets. It enables the entire workflow from sprint zero to release, bundles powerful interaction capabilities, and even helps you deploy apps. More importantly, it’s all simple, making the learning curve comfortable even for beginners. As you start to build your next Ext JS 5 app, remember that someone will use it on a tablet and they’re gonna love it.

modus-create-teaser.png 3 Comments   Read more

Announcing Public Beta of Ext JS 5

We are extremely excited to announce that the beta version of Sencha Ext JS 5 is available for public access and evaluation. This beta release enables you, our Sencha community, to test and evaluate our Ext JS 5 work in progress. For all the Ext JS developers out there, this a great opportunity to help make this the best Ext JS release ever.

And since this is a beta, we advise against putting it into production just yet.

Goals for Ext JS 5

We’re proud that Ext JS has become the industry standard for data-driven single-page applications. Engineered to grow with teams and projects, Ext JS powers applications that have successfully scaled to hundreds of screens and hundreds of thousands of lines of code. For intelligible, maintainable web applications, with clear separation of structure, behavior and visuals, we believe that the architected, component-centric approach of Ext JS is simply unbeatable.

When we sat down to design Ext JS 5, we wanted to take everything that made Ext JS great and make it even better. We had three themes for our development process. Our first theme was to Make Multi-Device Development Real. Ext JS 5 is our first release that allows the same code to power both desktop and touch device experiences, with a gesture system inspired by Sencha Touch. There are two fresh multi-device themes, so our rich set of UI components look and feel at home on both touch and desktop screens.

Our second theme was Evolution not Revolution. Perhaps the most important thing that hasn’t changed in Ext JS 5 is that we continue to make Internet Explorer 8 a first-class browser. We made this decision because a solid majority of you told us that IE8 support will continue to be a requirement for your applications through 2015 and beyond. We’ve also made smooth upgrades from Ext JS 4 a priority. As we’ve added and upgraded functionality, we’ve minimized breaking changes in our public APIs.

Our third and final theme was Developer Productivity. As we designed the new two-way data binding architecture, our goal was to vastly reduce the amount of code developers had to write to implement common UIs. In many cases, tasks that used to require several listeners can now be reduced to a few binding directives — which can be seen in some of our Kitchen Sink examples. Through the use of declarative listeners, views can now often be completely code-free, allowing developers to not only cut code size but maintain better separation of concerns at the same time.

As you can tell, we’re proud to release this beta to the community and hope that when compatibility, productivity and user experience matter most, Ext JS will continue to be your proven way to deliver the best engineered applications to your end users, customers and clients.

Announcing Public Beta of Ext JS 5

Now, on to the new features! Ext JS 5 has a myriad of new features and improvements. Here are some of the best:

  • Two-way data binding is a new mechanism that allows changes made in the view to be automatically written back to the model (and vice versa) without the need for custom event handlers.
  • Grid gadgets are new lightweight components useful for embedding within grid cells. Widgets and buffered updates make Ext JS grids even better, enabling richer data visualization and real-time data updates.
  • Touch-optimized charts is a new charting package that comes with features like 3D charts, financial charts, and multi-axis. It also has faster performance, cleaner code and a great experience on touch-screen devices. (The existing chart package is available as a separate package, so you can still use it.)
  • Routing allows application deep linking by translating your application’s URL into controller actions and methods.

There are numerous other enhancements and improvements related to MVC and performance in general. Read What’s New in Ext JS 5 for an exhaustive view of every new feature.

Another goal of Ext JS 5 is to converge much of the framework core between Ext JS and Sencha Touch. In Ext JS 5, we methodically converged code for the class system, data package, and feature/environment detection into a common core, so it can be shared across Ext JS and Sencha Touch. These shared components enable the creation of applications that share resources regardless of the framework.

Ext JS 5 supports IE8+ and the latest tablet platforms such as iOS6/7, Chrome on Android 4.1+, and Win 8 touch-screen devices (such as Surface and touch-screen laptops) running IE10+.

Beta Availability

Ext JS 5 beta is available for download immediately along with a beta version 5 of Sencha Cmd which is available for Windows, Mac OS X, Linux/64, and Linux/32. Check out our examples on a tablet.

We’re working hard to release Ext JS 5 in finished form as soon as possible, and we need your help and feedback to make that happen. Try out our new kitchen sink examples, migrate one of your smaller apps and report bugs, issues, or errors on the Ext JS 5 Public Beta forum. We look forward to your feedback.

20140401-ext-js-5-teaser.jpg 117 Comments   Read more

Addressing Mobile Data Security (Part 2)

In Part 1 of this series, we explored how the increasing cost of data breaches coupled with the risk of increased mobility poses formidable challenges for IT-based organizations. The post discussed how MDM/MAM solutions can help to provide a basic level of protection, but fall short in certain key areas. In particular, MDM and MAM solutions do a poor job of providing application-level security unless organizations choose to rebuild or recode their applications. Organizations should complement their MDM/MAM deployments with solutions that use strong encryption and digital signatures to protect their sensitive data.

Using strong encryption and digital signatures can add another layer of protection if a mobile device containing sensitive data is lost or stolen. MDM/MAM solutions typically provide remote wipe of the device in the event of loss or theft. However, because this feature works at the device level, it erases all data on the device, including the end user’s personal data. This lack of granularity in MDM solutions is often cited as a barrier to end user adoption of corporate BYOD programs.

An ideal solution instead would be to manage cryptographic data security, maintain separation between personal and professional data, and constrain the scope of the remote wipe capability to the organization’s proprietary data, leaving the end user’s personal data untouched.”

An ideal solution instead would be to manage cryptographic data security, maintain separation between personal and professional data, and constrain the scope of the remote wipe capability to the organization’s proprietary data, leaving the end user’s personal data untouched. In addition, this approach would potentially address the privacy concerns many users have about turning their personal devices over to the control of their employer’s IT department.

Another growing threat to mobile data security is the explosion in mobile malware and network-borne threats. These are additional threats, under which MDM solutions fall short. Because an MDM solution works at the device level, if mobile malware manages to get on the device, it can access and exfiltrate proprietary data on the device. If the device is connected via a device-wide IPSec VPN to data center assets, the malware could potentially spread or gain access to data center resources as well. If the data were secured using fine-grained encryption (i.e. each data chunk encrypted with its own unique, long encryption key) then a malware data thief would have a very difficult time recovering anything useful in a timely manner.

Similarly, if a user connects to the internet via an insecure WiFi hotspot, all proprietary data should be encrypted on the wire or face the risk of a man-in-the-middle attacker gaining unauthorized access to sensitive data. An application level VPN can help to protect data-in-motion from this sort of threat. Unlike the device-wide VPN policy, an MDM solution can manage the application-level VPN and prevent other applications on the device from accessing intranet resources.

Managing devices can provide a minimum baseline for security compliance. However, organizations should focus instead on deep security of their applications and data itself, regardless of whether it resides on IT-issued or user-owned devices. This data-centric approach is especially important in scenarios where non-employee collaborators such as partners, contractors, and consultants require access to sensitive data.

In these scenarios, MDM/MAM solutions are particularly ineffective because IT cannot realistically mandate these external entities to subscribe to their particular MDM/MAM policies and applications. By combining encrypted storage with encrypted transmission at the application layer, an organization can help to ensure that their data is managed and as safe as possible from potential security threats. The solution should provide these benefits even when authorized business collaborators, such as partners and contractors, who are not subject to corporate IT policies access the data.

To learn more about how Sencha solutions can help to address mobile data security challenges, please click here.

20140227-space-security.jpg 2 Comments   Read more

Introducing Sencha.com/videos

Sencha Video Chanel

Over the years we’ve been producing videos on building better HTML5 apps, JavaScript tips, and thought-provoking conversations from around the world. Most of these videos have been available on our Vimeo channel, but now we’ve created a channel on our own site to make them easier to find.

Check it out at www.sencha.com/videos.

Here are some of our favorites…

20140213-sencha-video-preview.jpg 1 Comment   Read more

Automating Unit Tests

One of the first questions I always hear when starting with a new client is “How can I build unit tests for my application?”

It’s obvious that many people understand the benefits of unit tests—developers want to minimize the number of bugs in their code and managers want to reduce the amount of time required to test an application before release. Although the concept of unit testing has existed for years, software teams are only now beginning to explore building tests for their Rich Internet Applications (RIAs).

In my experience, it’s obvious that most people don’t fully understand what it means to build unit tests for RIAs. Considering there are few tutorials explaining how to accomplish this, I wanted to share a recent experience with the community in hopes that it will stimulate ideas and discussion.

Keep an open mind as you follow along with this post and think about how these examples might fit into your own processes. This implementation is one of any number of possible solutions, and I don’t attempt to solve every problem. That being said, implementing unit tests into your project will produce cleaner, more stable code and will reinforce coding standards throughout your organization.

I. Unit Testing Web Applications: An Overview

Layers Diagram

In the diagram above, the “Presentation Layer” represents the user interface – which in the case of RIAs is frequently a JavaScript-driven DOM. This is the case for most Ext JS and Sencha Touch applications.

When building unit tests for RIAs, it’s important to remember that the user interface (the “presentation layer”) is very different from the supporting layers of the application.

The UI accepts random input from the user and is expected to look AND behave the same across many environments (which is both subjective AND objective). One language (JavaScript) performs multiple tasks (logic and presentation). Because its code is never compiled, syntax errors in JavaScript are often not discovered until runtime.

Thus developers more familiar with server-side unit tests often fail to realize the complexity involved in writing unit tests for JavaScript-driven applications. As a result, we cannot build unit tests for the presentation layer in the same way we would for the underlying data-driven tiers of an application.

Because the presentation layer has multiple responsibilities, it is important to separate unit tests into the following three areas:

  • Syntax Checks – Syntax checks are not exactly unit tests because there is no logic being tested. Instead we analyze our code for syntactical errors – errors that may or may not be caught before application execution.
  • Unit Tests – True to its contemporary meaning within software development, unit tests are a series of objective logic tests. Unit tests attempt to isolate small pieces of our code: given specific inputs, unit tests expect specific outputs. In this manner unit tests are essentially mathematical proofs (remember those from high school?) that confirm what our business logic is supposed to do.
  • UI Tests (aka Integration Tests) – UI Tests are not the same as unit tests. UI Tests attempt to subjectively verify that elements on the screen behave (and/or look) as expected when a user performs a given action. There is no math or logic involved: the tests render the environment as a whole (containing all runtime dependencies) and wait to verify that the DOM has changed in a desired way. You can think of these tests as a robot manually testing the application.

I do not attempt to solve the problem of UI Tests in this post, but there are helpful links are included at the end if you’re interested.

II. A Sample Application

The key to implementing unit tests is to automate the process – if the tests aren’t run every time the code changes (or at some regular interval), the tests become ineffective and useless.

I have created a sample project that uses shell scripts to run each individual part (syntax checks and unit tests). These scripts return status codes upon success and failure.

The specific process to integrate these automated tests may be quite different at every company. The shell scripts might provide automation by:

  • being integrated into a build process (e.g. via Ant)
  • being integrated into source control hooks (e.g. a Git pre-commit hook on your local machine)

III. Pre-Requisites

The sample project (and the concepts explained below) assume a certain degree of knowledge on the following tools:

  • Sencha SDK Tools (v2.0.0b3) – a suite of automation tools assisting with application creation, development and deployment
  • PhantomJS (v1.4.1) – a headless WebKit browser controller via an easy JavaScript API
  • JSLint (v2012-05-09) – a JavaScript code quality tool
  • PhantomLint (v1.2.1) – an add-on to Phantom.js that automatically lints all JavaScript files in a project
  • Jasmine (v1.2.0) – a behavior-driven development framework for testing JavaScript code

The shell scripts in the sample project were targeted towards Mac OSX/Linux users. However, Windows batch (.bat) files or Ant scripts can easily accomplish the same thing and should be easy to create.

Also, if you’re new to the world of unit testing I would highly recommend the book Test Driven JavaScript Development by Christian Johansen.

IV. Syntax Checks

While there are a variety of syntax-checking tools available for JavaScript, perhaps the most widely recognized is JSLint. Those of you familiar with the tool should remember that “JSLint will hurt your feelings” – it complains about everything! On the other hand, it is also highly configurable and helps our code be clean, stable and consistent.

Because JSLint is written in JavaScript, it is traditionally run in the browser on Douglass Crockford’s website (http://www.jslint.com). Although this manual process is sometimes convenient, it is difficult to run against multiple files and impossible to automate.

A better solution is to use PhantomJS – a headless WebKit browser that provides the web environment necessary to run JSLint and our own JavaScript code. Additionally, PhantomJS can access the filesystem; this allows us to execute multiple files against JSLint and report back some success or failure status.

To further simplify the process of checking all of our JavaScript files, I have incorporated a pet project of mine called PhantomLint which logs errors to an output file. In this way, a failure status can alert developers to take corrective action.

Taking a look in the sample project under /tests/, you should see a shell script named “run_lint.sh”. This script launches the PhantomJS environment and initializes PhantomLint for us (JSLint-Runner.js). Given its configuration options, PhantomLint then dives into the filesystem to test our code against JSLint. Any errors are then output to a text file.

If you run the shell script, you should notice a single error in our application code:

../app/MeetupApiUtil.js
     Line #: 37
     Char #: 21
     Reason: Unexpected 'else' after 'return'.

In this case, JSLint tells us that we have a redundant “else” statement.

V. Unit Tests

There are a variety of JavaScript unit test frameworks currently available, and I chose Jasmine for this sample app. Why Jasmine? It is one of the more popular frameworks currently available, it has an active development community, and Sencha uses it internally to test our own code. Jasmine also has a very fluent API – this makes our test suite easy to understand. By nesting test conditions appropriately, we can build very powerful and descriptive test suites.

The tests can be run locally by visiting the “spec_runner.html” file under the /tests/ folder in one’s browser. The individual test files are located under the /tests/app/ directory.

Let’s start by looking at the class ChicagoMeetup.MeetupApiUtil. This class is ideal for unit testing because it has very few dependencies and doesn’t directly interact with the DOM; it is simply a collection of utility methods that perform logical operations.

Taking a look at the tests inside /tests/app/MeetupApiUtil.js you can see how the unit tests objectively analyze the methods for this class. Each test condition provides a specific input value and expects a specific output value.

describe('ChicagoMeetup.MeetupApiUtil', function() {
 
        describe('getUsersUrl() method', function() {
 
                it('should be a function', function() {
                        expect(typeof ChicagoMeetup.MeetupApiUtil.getUsersUrl).toEqual('function');
                });
 
                it('should return a string', function() {
                        expect(typeof ChicagoMeetup.MeetupApiUtil.getUsersUrl()).toEqual('string');
                });
 
        });
 
        //etc...
});

The ChicagoMeetup.MeetupApiUtil class and the related unit tests are a terribly simple example – in fact there’s very little logic involved. More often than not, we want to build unit tests for custom components in our Sencha applications. How can we achieve this?

Consider the class ChicagoMeetup.view.Events in our sample application. This is a custom class, extended from Ext.grid.Panel, that contains some specific methods and behavior for our app.

In our test code (/tests/app/view/Events.js) we first create setup and teardown methods that provide fresh instances of our custom component for each test case. We do this to avoid polluting our test environment with abandoned objects and DOM elements.

describe('ChicagoMeetup.view.Events', function() {
 
        //reusable scoped variable
        var eventGrid = null;
 
        //setup/teardown
        beforeEach(function() {
                //create a fresh grid for every test to avoid test pollution
                eventGrid = Ext.create('ChicagoMeetup.view.Events', {
                        renderTo : 'test' //see spec-runner.html to see where this is defined
                });
        });
 
        afterEach(function() {
                //destroy the grid after every test so we don't pollute the environment
                eventGrid.destroy();
        });
 
        it('should inherit from Ext.grid.Panel', function() {
                expect(eventGrid.isXType('grid')).toEqual(true);
        });
 
        //etc...
});

It is important to note that we temporarily render our custom component to the DOM for each test (via the “renderTo” config). We do this in order to test any logic that might depend on the DOM – but the key is to destroy these components in-between tests so the greater test environment is not polluted (negatively affecting subsequent tests).

Although we are rendering the component to the DOM, I have to re-emphasize that we are not using Jasmine to build UI (or integration) tests. Jasmine doesn’t care what the components look like – our unit tests are only here to analyze the business logic.

Now that we understand how to properly unit test our components, the next step is automating this process. Similar to how we automated our syntax checks, we will again use PhantomJS to run our unit tests and output failure messages to a log file.

Taking a look in the sample project under /tests/, you should see a shell script named “run_jasmine.sh”. This script launches PhantomJS and initializes the Jasmine parser for us (Jasmine-Runner.js). After our tests have run, any test failures are output to a text file.

If you run the shell script, you should notice a single test failure:

Spec: linkRenderer() method
Description:
     - should return a string (HTML link snippet)
Failure Message:
     - Expected 'string' to equal 'function'.

In this case, Jasmine tells us that a test against linkRenderer() failed. We expected that this method would return a function, but our test case encountered a string. This particular example fails because the spec incorrectly expected “function” – which demonstrates that unit tests can contain errors themselves!

describe('linkRenderer() method', function() {
 
        it('should return a string (HTML link snippet)', function() {
                var testUrl = 'http://www.sencha.com';
 
                expect(typeof eventGrid.linkRenderer).toEqual('function');
                expect(typeof eventGrid.linkRenderer(testUrl)).toEqual('function'); //THIS SHOULD FAIL! We should have written toEqual('string')
 
                //TODO: more robust regular expression checks to ensure this is *actually* an HTML link tag, correctly formatted
        });
 
});

It is unrealistic and nearly impossible to achieve 100% code coverage. Because unit tests are designed to test small pieces of code in isolation, it becomes very difficult to write good tests for pieces with many dependencies or major DOM interactions. Try to focus on problem areas or base classes, and write tests that check for bugs as they pop up (to prevent regressions).

VI. UI Tests

As I mentioned earlier, I am not attempting to solve the problem of UI Tests in this post. Testing the look and the complex interactions of an application is a humongous task, and is a topic better suited for its own dedicated tutorial.

That being said, here are some of my thoughts on accomplishing UI Tests:

  • Building UI tests for dynamic RIA’s is sufficiently difficult because the DOM is always changing in unpredictable ways. Tools like Selenium use XPATH or CSS selectors to verify “success” – but because the DOM is unpredictable, the tests written for these tools become very brittle. Thus maintaining your tests often takes more time than creating new features.
  • Many prominent UI developers prefer to use “specification” rather than “UI tests” for exactly these reasons. A good resource for you is the book “Specification by Example”, in which tools like Cucumber are recommended.
  • Siesta is becoming a more popular tool for automated UI testing and is certainly worth a look.

VII. Conclusion

Unit tests are an important part of the software development process. By clearly defining what we expect from our code, unit tests allow us to develop a high degree of confidence that our applications will function as intended. Automating our unit tests reduces the number of bugs and decreases the amount of time we need to spend manually testing our code.

Take a look at the sample project on GitHub and consider how this solution might integrate with your own processes. This post is meant to foster ideas and discussion within the community – so please chime in with questions, comments and solutions of your own! Feel free to fork the sample project and add or edit the examples!

20120801-unit-tests.jpg 30 Comments   Read more

Sencha Touch oData Connector and Samples for SAP

Today we’re releasing the Sencha Touch oData Connector for SAP, available on the Sencha Market. We’ve partnered with SAP to make it easier for SAP customers to build HTML5 applications using Sencha Touch. Sencha Touch is often used to build apps that mobilize enterprise applications, and using the oData Connector, Touch developers can now connect to a variety of SAP mobile solutions such as Netweaver Gateway, the Sybase Unwired Platform, and more. We announced our partnership with SAP earlier this year and have been working actively with SAP to build this shared capability to make it easy for developers to quickly build rich mobile enterprise applications.

The download comes with a getting started guide, a sample application, and the Sencha Touch oData Connector for SAP. The sample application, Flights Unlimited, connects to a hosted demo SAP Netweaver server and uses the oData Connector to query flight times, passenger manifests, pricing information and more. The application is built with Sencha Touch, so it’s pure HTML5 and can be deployed to the web, or hybridized with Sencha Touch Native Packaging for distribution to an app store. It’s a complete and comprehensive application that shows how developers can leverage the power of Sencha Touch and SAP mobility solutions together.

If you want to learn more, SAP hosted a webinar from SAP Labs in Palo Alto where we talk with SAP about how we’re enabling the oData capability and show off the Flights Unlimited demo. The recording of the webinar is available for streaming online.

We’re excited to see what our global development community will build with the new oData for SAP connector!

20120730-SenchaSAP.png 19 Comments   Read more

Flex to Sencha: The Opportunity

In my professional career I have never witnessed a disruptive shift as large as the adoption of HTML5 as an application medium. Within this movement, Sencha is focused on building enterprise-grade frameworks, tools, and services to allow developers to deliver HTML5 applications on today’s mobile and desktop browser runtimes. Today Sencha is launching a [fast-track program](http://pages.sencha.com/flex-to-sencha.html “Flex to Sencha”) for Flex Developers looking to develop HTML5 applications.

Having worked on Flex at Adobe, I have a deep respect for Flex as a technology and ecosystem. Flex is great technology but the foundational dependency on Flash Player is forcing many projects to re-architect towards HTML5. Within this disruption, I believe there is a great opportunity for Flex developers to learn a new technology, leverage existing knowledge, and deliver great application experiences with Sencha. I also believe that Flex developers have the opportunity to define and lead the movement toward HTML5 applications as they bring years of experience building world class applications with components, classes, MVC, and a futuristic version of ECMAScript.

The developer paradigms of Sencha and Flex are very similar and developers who know Flex will learn Sencha frameworks quickly and find their existing knowledge of component development instantly valuable. While the syntax and architecture are different, I keep finding patterns and concepts that match Flex perfectly but are suited to the interpreted model of web development and deployment. Within Sencha frameworks, Flex developers will find a modern class system with package support, a rich set of UI components, model classes for loading data, declarative component instantiation (xtype), and MVC integrated into the framework.

![Sencha Frameworks](http://pages.sencha.com/rs/sencha/images/flex-sencha-icons-380×77.png)

Today Sencha is launching a fast-track program for Flex Developers looking to develop HTML5 applications. We begin with a [Flex to Sencha Webinar](http://pages.sencha.com/flex-to-sencha-webinar.html “Flex to Sencha Webinar”) on Tuesday, February 14, and will continue with a [Flex to Sencha Road Show](http://pages.sencha.com/flex-to-sencha-roadshow.html “Flex to Sencha Road Show”) meeting with Flex user groups and Flex/Flash conferences throughout the year. We are also working on technology additions to Sencha frameworks including AMF and SOAP WebService support direct from JavaScript. For those that prefer visual tools, I also want to highlight the upcoming [Sencha Designer 2](http://www.sencha.com/blog/sencha-designer-2-beta-announcement/ “Sencha Designer 2″) which helps you build both desktop and mobile applications visually.

Flex to Sencha Events:

– ###[Webinar Registration](http://pages.sencha.com/flex-to-sencha-webinar.html “Flex to Sencha Webinar Registration”)

– ###[Roadshow Registration](http://pages.sencha.com/flex-to-sencha-roadshow.html “Flex to Sencha Road Show Registration”)

I look forward to highlighting Sencha’s object-oriented and component based solution to building HTML5 applications to the Flex ecosystem. Having built many applications myself with Flex, I know that you can be successful building HTML5 applications with Sencha.

flex-to-sencha-html5.jpg 13 Comments   Read more

The Sencha Hackathon Recap

The Sencha Hackathon Recap There are hackthons. And then there is the SenchaCon hackathon.

Day three of our awesome conference in Austin last week really reaffirmed our belief in the strength of the Sencha community. I’ve rarely seen such a concentration of talent, enthusiasm, and friendship–not mention amazing productivity–come together so well.

We wanted to stimulate competition and organized a number of prize categories for the event. The Google Chrome team sponsored the event as a whole, and also kindly offered Chromebook hardware as a prize for ‘Best use of HTML5 API’. We also offered ‘Best Desktop’ and ‘Best Mobile’ categories, as well as spot prizes for additional interesting application categories.

Once our introductory pleasantries were over, we decided to make sure that teams could get coding as quickly as possible. The amicable vibe of the whole conference helped immediately, as cohesive groups quickly formed around exciting ideas that community members proposed.


Hackathon hackers.
Arthur Kay

Hackathon hackers. Photos by Nils Dehl.

Caffeine, power, and a decent wifi connection are the other ingredients required to keep teams working hard during the day. We just about managed all three, and certainly the arrival of the Red Bull support team helped any flagging programmers get through the final few hours.

By the time we reached 4pm–after over 6 hours of frantic coding, an astonishing 20 teams were ready to jump up onto our vast stage and present the results.

And what results they were: we had news visualizations, signal strength detectors, web-based file sharing, games, database administration tools, collaborative drawing and learning tools, social networks, and many many more. The variety was almost as amazing as the quality.


Hackathon hackers.
Andrea Cammarata

After a very tough judging session, we announced the main winners. And they were:

Best use of an HTML5 API: Lamp Post

Multi-user music file sharing using Chrome’s File API, featuring real-time chat and notification of shared directories using a Node JS backend with node-extjs. The team won a Chromebook and $500, kindly sponsored by Google Chrome.

Best Desktop App: Code Cowboys

A crowd-sourced unit testing application for Ext JS and Sencha Touch. The team won an iPad 2 and $500.

Best Mobile / Tablet App: Presencha

Upload slides in PDF form, and present live to any device for collaborative viewing by an audience. The team won an iPad 2 and $500.

The “Presencha”:http://www.presencha.com/ team have made their code available on “GitHub”:https://github.com/cianclarke/Presencha, and are aiming to have their service available soon.

We then had a number of additional categories which teams were gunning for. Each of these teams won $250.

Best Social App: LinkedUp
A mobile social network for entrepreneurs and innovators.

Best Austin-related App: Dirty 6th
Shows bars, clubs and other venues near a user’s location or and in downtown Austin.

Best Educational App: iKnow
A mobile application to learn or memorize anything

Best App by a Novice Team: Doodleshare
A screen-sharing application to allow games such as Charades and Pictionary on mobile and tablet devices.

We also had two discretionary prizes for apps that impressed the judges above and beyond these categories. These were TouchMySql and the German Rockstars team.

At events like this, we hope that every one feels they are a winner! If you were there, I hoped you enjoyed the experience of being able to rub shoulders with your peers and the Sencha teams. It was an awesome way to wrap up the whole conference, and we look forward to hosting you all next year!

senchacon-hackathon.jpg No Comments   Read more

The Sencha Hackathon Recap

There are hackthons. And then there is the SenchaCon hackathon.

Day three of our awesome conference in Austin last week really reaffirmed our belief in the strength of the Sencha community. I’ve rarely seen such a concentration of talent, enthusiasm, and friendship – not mention amazing productivity – come together so well.

We wanted to stimulate competition and organized a number of prize categories for the event. The Google Chrome team sponsored the event as a whole, and also kindly offered Chromebook hardware as a prize for ‘Best use of HTML5 API’. We also offered ‘Best Desktop’ and ‘Best Mobile’ categories, as well as spot prizes for additional interesting application categories.

Once our introductory pleasantries were over, we decided to make sure that teams could get coding as quickly as possible. The amicable vibe of the whole conference helped immediately, as cohesive groups quickly formed around exciting ideas that community members proposed.

Caffeine, power, and a decent wifi connection are the other ingredients required to keep teams working hard during the day. We just about managed all three, and certainly the arrival of the Red Bull support team helped any flagging programmers get through the final few hours.

By the time we reached 4pm – after over 6 hours of frantic coding, an astonishing 20 teams were ready to jump up onto our vast stage and present the results.

And what results they were: we had news visualizations, signal strength detectors, web-based file sharing, games, database administration tools, collaborative drawing and learning tools, social networks, and many many more. The variety was almost as amazing as the quality.

After a very tough judging session, we announced the main winners. And they were:

Best use of an HTML5 API: Lamp Post
Multi-user music file sharing using Chrome’s File API, featuring real-time chat and notification of shared directories using a Node JS backend with node-extjs. The team won a Chromebook and $500, kindly sponsored by Google Chrome.

Best Desktop App: Code Cowboys
A crowd-sourced unit testing application for Ext JS and Sencha Touch. The team won an iPad 2 and $500.

Best Mobile / Tablet App: Presencha
Upload slides in PDF form, and present live to any device for collaborative viewing by an audience. The team won an iPad 2 and $500.

We then had a number of additional categories which teams were gunning for. Each of these teams won $250.

Best Social App: LinkedUp
A mobile social network for entrepreneurs and innovators.

Best Austin-related App: Dirty 6th
Shows bars, clubs and other venues near a user’s location or and in downtown Austin.

Best Educational App: iKnow
A mobile application to learn or memorize anything

Best Social App: LinkedUp
A mobile social network for entrepreneurs and innovators.

Best App by a Novice Team: Doodleshare
A screen-sharing application to allow games such as Charades and Pictionary on mobile and tablet devices.

We also had two discretionary prizes for apps that impressed the judges above and beyond these categories. These were TouchMySql and the German Rockstars team.

At events like this, we hope that every one feels they are a winner! If you were there, I hoped you enjoyed the experience of being able to rub shoulders with your peers and the Sencha teams. It was an awesome way to wrap up the whole conference, and we look forward to hosting you all next year!

No Comments   Read more