Home > Articles > Home & Office Computing > Entertainment/Gaming/Gadgets

  • Print
  • + Share This
This chapter is from the book

Testing and Debugging PhoneGap Applications

Each of the mobile platforms supported by PhoneGap has a mechanism a developer can use to test and, in the unlikely event your code has bugs, debug PhoneGap applications. In general, you can load a PhoneGap application into a device simulator or emulator, provided as part of the mobile platform’s SDK, or you can load an application onto a physical device. There are also third-party solutions you can use to test your PhoneGap applications within a desktop browser interface.

Running a PhoneGap Application on a Device Simulator or Emulator

Each smartphone operating system supported by PhoneGap has a device emulator or simulator (E/S) provided by the originator of the OS. In some cases, what’s provided is a generic emulator that simply mimics the capabilities of the specific OS version, while for other mobile platforms there are simulators available that mimic specific devices. Either way, there’s a software-only solution available that developers can use to test PhoneGap applications in an almost real-world scenario (I’ll explain “almost real-world” in the following section).

An E/S is typically included with the native development tools for each mobile platform, but in some cases there are options that can be downloaded individually. Research In Motion, for example, includes a set of simulators with each BlackBerry Device Software version SDK but also provides individual downloads for specific BlackBerry Device Software versions or for older devices that have software updates available for them. Either way, there are likely options available for each and every device or device OS you want to test your application on. The chapters that follow provide detailed information on how to configure a development environment for each of the mobile devices platforms supported by PhoneGap. That’s where you will find instructions on how to test PhoneGap applications on the appropriate E/S for the target platform.

Running a PhoneGap Application on a Physical Device

While the device E/S is a great option for developer and system testing of a PhoneGap application, final testing should always be performed on a physical device. As good as these options are, there is always something that doesn’t work quite right on a simulator or emulator.

To run a PhoneGap application on a physical device, you will create the PhoneGap application first using the native SDK or package the application for platforms that use a widget approach. Once you have a deployable application, you will connect the device to your development computer via a Universal Serial Bus (USB) cable and transfer the application to the mobile device using some component of the native SDKs. The process varies depending on the mobile platform you are working with.

For iOS applications, for example, Apple requires a special provisioning process for every iOS device on which you want to install your application. The process requires membership in Apple’s developer program and involves the Xcode development environment, Apple’s developer portal, a provisioning profile, and a physical device.

For Android and BlackBerry devices, the native SDK includes command-line utilities you can use to copy an application to a target device. There’s no special provisioning process; you simply connect the device to the developer computer, issue the command, and test away. In some cases, you can deploy to devices directly from the Eclipse IDE. For Android devices, there are steps you must complete to configure the device for testing applications. On BlackBerry, you’ll need to secure a set of signing keys (they’re free at https://bdsc.webapps.blackberry.com/java/documentation/ww_java_getting_started/Code_signing_1977871_11.html) and sign the application before it will run on a physical device.

Regardless of the platform you use, digging into the details of on-device testing is beyond the scope of this book. Please refer to the documentation for the appropriate native SDK for additional information about how to test applications on physical devices.

Leveraging PhoneGap Debugging Capabilities

As mentioned earlier, there are two types of PhoneGap applications: PhoneGap applications that consist of a web application packaged inside of a native application container (for Android, BlackBerry, iOS, and Windows Phone) and PhoneGap applications deployed simply as packaged web applications (on bada, Symbian, and webOS).

For the mobile platforms where PhoneGap applications are simply packaged web applications, the freely available native SDK typically includes support for debugging web content running in a device emulator or simulator. In the chapters that follow, you will find instructions on how to leverage native debugging tools for these platforms when testing PhoneGap applications. You will, however, need to refer to the native SDK documentation for detailed information on how to use these tools.

The problem with the native application options for PhoneGap is that the native tools designed to help developers debug applications for each platform are designed to debug native applications; they have none or limited capabilities for debugging web content that is packaged within native applications. The BlackBerry Web-Works development tools originally supported the ability to debug web content packaged within a BlackBerry WebWorks application (which is essentially what a PhoneGap application is on BlackBerry). In 2011, RIM abandoned the Eclipse and Visual Studio IDEs and switched to an entirely command-line-driven approach.

To help debug your PhoneGap applications, you can fill your code with calls to the alert() function. This is what I have always called a poor man’s debugger, but it works quite well for certain types of application debugging tasks. If you see an event that’s not firing within your application or some variable that’s not being set or read correctly, you can simply insert an alert that displays a relevant message and use that to see what’s going on. There’s an example of this approach in the HelloWorld2 application shown earlier with the use of PhoneGap’s navigator.notification.alert("") function. In this case, I used the alert to help debug what was happening in the onDeviceReady() function. It seemed to be working on Android, but not BlackBerry, so I used the alert to help confirm my suspicion and to help test different approaches as I attempted to fix the problem.

The problem with this approach is that when you fill your buggy code with alerts, you’re constantly interrupting the application flow to dismiss the alerts as they come up. For a simple problem, this approach works pretty well, but when debugging more troublesome errors, you will need an approach that allows you to let the application run and then analyze what is happening in real time or after the application or a process within the application has completed, without interrupting the application. PhoneGap applications can do this through the JavaScript console object implemented by the WebKit browser rendering engine.

Using the console object, developers can write messages to the browser’s console, which can be viewed outside of the running program through capabilities provided by the native SDKs or device simulators or emulators. The console object has scope at the window level, so it’s essentially a global object accessible by any JavaScript code within the application. WebKit supports several options; the most common ones used are as follows:

  • console.log(“message”);
  • console.warn(“message”);
  • console.error(“message”);

Example 2-1 shows a sample application that illustrates the use of this feature.

Example 2-1

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width,
      height=device-height, initial-scale=1.0,
      maximum-scale=1.0, user-scalable=no;" />
    <meta http-equiv="Content-type" content="text/htm1;
      charset=utf-8">
    <script type="text/javascript" charset="utf-8"
      src="phonegap.js"></script>

    <script type="text/javascript" charset="utf-8">

      function onBodyLoad() {
        document.addEventListener("deviceready", onDeviceReady,
          false);
      }

      function onDeviceReady() {
        //Just writing some console messages
        console.warn("This is a warning message!");
        console.log("This is a log message!");
        console.error("And this is an error message!");
      }

    </script>
  </head>
  <body onload="onBodyLoad()">
    <h1>Debug Example</h1>
    <p>Look at the console to see the messages the application
    has outputted</p>
  </body>
</html>

As you can see from the code, all the application has to do is call the appropriate method and pass in the text of the message that is supposed to be written to the console.

In some cases, the browser component executing your application’s web content won’t throw an error if you try to do something that’s not supported in your Java-Script code (calling a PhoneGap API function that doesn’t exist, for example, because you’ve misspelled it). In this scenario, simply wrap the errant call in a try/catch block so your application will have a chance to write its error to the console, as shown in the following example:

try {
  console.log("Validating the meaning of life");
  somefunctioncall("42");
} catch (e) {
  console.error("Hmmm, not sure why this happened here: " +
   e.message);
}

Figure 2-6 shows the messages from Example 2-1 highlighted in the Xcode console window. This window is accessible while the program is running on an iOS simulator, so you can debug applications in real time.

Figure 2-6

Figure 2-6 Viewing console messages in Xcode

When working with the BlackBerry simulator, you can access the logs by holding down the simulator’s Alt key and typing lglg. The simulator will display the Event Log, as shown in Figure 2-7.

Figure 2-7

Figure 2-7 BlackBerry Event Log application

When you open an Event Log entry, you can see the details behind the entry, as shown in Figure 2-8. Press the keyboard’s n and p keys to navigate to the next and previous entries in the log.

Figure 2-8

Figure 2-8 Viewing console messages on BlackBerry

Within the BlackBerry Event Log application, you have the ability to clear the log, filter what’s displayed in the log, and copy the contents of the log to the clipboard so you can use them in another application or send them to yourself via email. Additionally, when working with a physical device, you can connect the device to your development system and use the BlackBerry Java Loader application (javaloader.exe) to copy the logs from the device. Many of these options are described in detail in my other mobile development book, BlackBerry® Development Fundamentals (www.bbdevfundamentals.com).

The Android SDK includes utilities that allow a developer to monitor log activity, while an application runs within an Android emulator. This functionality is provided by the LogCat utility, which is an integral part of the Eclipse plug-in but also available through the command line or a stand-alone utility.

To open the LogCat window in Eclipse, open the Window menu, select Show View, and then select Other. In the dialog that appears, expand the Android category and select LogCat, as shown in Figure 2-9, and then click OK. Eclipse will open a new pane in the messages area of the IDE, as shown in Figure 2-10.

Figure 2-9

Figure 2-9 Eclipse Show window dialog

Figure 2-10

Figure 2-10 Eclipse messages area

This pane will display all messages generated by the Android device emulator as well as console messages written by your PhoneGap application; you can see the three messages written by the sample application. Use the V (verbose), D (debug), I (info), W (warning), and E (error) buttons at the top of the pane to filter the contents of the pane as needed to allow you to more quickly locate the entries you are looking for while debugging an application.

Google also offers a stand-alone utility called the Dalvik Debug Monitor Server (DDMS) that you can use to monitor the Android emulator console when testing PhoneGap applications outside of the Eclipse IDE. To launch the DDMS utility, you must first launch an Android emulator. Once the emulator is running, open a file explorer (Finder on Macintosh or Windows Explorer on Windows), navigate to the Android SDK tools folder, and execute the DDMS utility located therein. The file is called ddms.bat on Microsoft Windows and ddms on Macintosh.

When the utility launches, it will display a window similar to the one shown in Figure 2-11. At the top of the utility are windows that show the different processes running in the emulator on the left and a list of additional options on the right. The lower half of the application’s window displays the same LogCat pane from the Eclipse plug-in.

To access the LogCat content from the command line on Windows, open a command prompt, navigate to the Android SDK platform-tools folder, and issue the following command:

adb logcat

On Macintosh, open a terminal window, navigate to the Android SDK platform-tools folder, and issue the following command:

./adb logcat
Figure 2-11

Figure 2-11 Android DDMS application window

The adb utility will connect to the emulator and retrieve and display in real time the contents of the logcat from the Android emulator, as shown in Figure 2-12. In the figure, the three console messages generated by the application are highlighted.

Figure 2-12

Figure 2-12 Viewing console messages on Android

Third-Party PhoneGap Debugging Tools

There’s a very active partner community supporting PhoneGap with additional tools for PhoneGap developers. In this section, I’ll introduce several of the available tools that help developers test and debug PhoneGap applications. This is by no means a complete list of options; refer to the PhoneGap wiki (http://wiki.phonegap.com) for information on additional tools that might be available.

Ripple Mobile Environment Emulator

When developing a PhoneGap application, it’s quite time-consuming to build the application and load it into a simulator or emulator for testing. The Ripple Mobile Environment Emulator (RMEE) is a freely available tool that helps alleviate this problem by providing a desktop browser–based interface you can use to test your PhoneGap applications. The RMEE emulates the execution of the PhoneGap APIs within the browser container. You should use the emulator for quick testing of PhoneGap application features during development and then switch to packaging/building PhoneGap applications and testing them on actual devices or device emulators or simulators for more thorough testing. The RMEE is not designed to replace testing on real devices, device simulators, or device emulators.

The RMEE is implemented as an extension to the Google Chrome browser, so before you can start using the emulator, you must first install the latest version of Chrome from www.google.com/chrome. Once you have Chrome up and running, launch the browser and navigate to http://ripple.tinyhippos.com. From the Tiny Hippos home page, click the Get Ripple link, and follow the prompts to install the latest version of the emulator.

Before you can start emulating PhoneGap within the RMEE, you must first configure the browser to allow the emulator access to files on the local file system. Open the Chrome browser, right-click the Ripple icon to the right of the browser’s address bar, and select Manage extensions. The browser will display a page similar to the one shown in Figure 2-13. Enable the “Allow access to file URLs” option for the RMEE as shown in the figure and then close the page by clicking the X to the right of the Extensions tab.

Figure 2-13

Figure 2-13 Configuring the Ripple Emulator in Google Chrome

Once the browser has been configured, open your application’s index.html file in the browser. You can press Ctrl+O on Windows or Command+O on Macintosh to open the File Open dialog. Once the page has loaded, you need to enable Ripple for the selected page. To do this, complete one of the following options:

  • Click the Ripple icon to the right of the browser’s address bar to open a window, allowing you to enable Ripple for the loaded page.
  • Right-click the page, open the Emulator menu, and then select Enable.
  • Append ?enableripple=true to the file URL to enable Ripple directly within the address bar when loading an application’s index.html file.

Once the RMEE is enabled for the loaded page, the browser will display a page, shown in Figure 2-14, that prompts you to identify which type of emulation you want to enable for this page. As you can see, the RMEE supports PhoneGap plus several other platforms and frameworks. Click the PhoneGap button to continue.

Figure 2-14

Figure 2-14 Enabling PhoneGap emulation in the Ripple emulator

At this point, the RMEE will display a page with the content from the index.html file rendered within the boundaries of a simulated smartphone screen, as shown in Figure 2-15. Wrapped around the simulated smartphone are properties panes that can be used to configure options and status for the simulated smartphone such as simulated device screen resolution, accelerometer, network, geolocation, and more.

Figure 2-15

Figure 2-15 PhoneGap application running in the Ripple emulator

You can click each of the tabs to expand the options for the tab and make changes to the simulated device’s configuration. At this point, you would simply click around within the simulated smartphone screen and interact with the options presented within your application. When you find a problem or a change you want to make within the PhoneGap application, simply return to your HTML editor, make the necessary changes, write the changes to disk, and then reload the page in the Chrome browser to continue with testing.

Weinre

Web Inspector Remote (Weinre) is a community-built remote debugger for web pages. It has been donated to the PhoneGap project and is currently implemented as part of the PhoneGap Build service. You can find the download files and instructions at http://phonegap.github.com/weinre. Weinre consists of a debug server, debug client, and debug target. The debug server runs on Macintosh or Windows, and the debug client runs in any compatible desktop browser.

For PhoneGap development, it allows a developer to debug a web application on physical device or a device emulator or simulator. To configure Weinre, perform the following steps:

  1. Install a debug server on a desktop computer.
  2. Launch the debug server.
  3. Windows only: Point a compatible desktop browser at the debug server.
  4. Connect the remote web application to the server.

The server component of Weinre consists of a stand-alone Macintosh executable or a Java JAR file for Windows. On Macintosh, load the debug server by double-clicking the application’s executable in Finder. The debug server and debug client are packaged together in the same application, so there are no additional steps needed to launch the debug client.

On Windows, the debug server consists of a single JAR file that, assuming Java is on the Windows Path, can be loaded using the following command:

java -jar path/to/weinre.jar

There are additional command-line options that can be passed to the JAR file while it’s loading to allow you to configure the host address the server will respond to, the server port number, and more. Refer to the Weinre documentation for additional information about the available command-line options. When the server starts, it will display a message indicating the URL to use to start the debug client; by default it should be http://localhost:8080. Point a compatible WebKit-based browser at the server to open the debug client.

To connect the PhoneGap application to the debug server, add the following <script> tag to the <body> section of the application’s index.html file,

<script src="https://debug_server:8080/target/
  target-script-min.js"></script>   

replacing the debug_server portion of the URL with the correct host name or IP address for the debug server. This provides the code needed for the PhoneGap application to upload information to the debug server. The Android emulator does not have the ability to connect to host-side resources using an IP address, so for the Android emulator, you must use the host address http://10.0.2.2, as shown in the following example:

<script src="https://10.0.2.2:8080/target/
  target-script-min.js"></script>

Figure 2-16 shows the debug server running on a Macintosh. On the bottom of the window are tabs that control the server while the toolbar on the top of the window contain options for the remote debugger client.

Figure 2-16

Figure 2-16 Weinre server/debug client on a Macintosh

The debug client provides the means to view and optionally manipulate many of the page elements and other aspects of your application’s web content. You can view the browser console, as shown in Figure 2-17, to see console messages written by the PhoneGap application, or you can change application values or properties to tweak the application while it’s running.

The available documentation for Weinre is pretty light, but since the project’s capabilities are based upon the Google Chrome Developer Tools, you can find additional information on the Google Code web site at http://code.google.com/chrome/devtools/docs/overview.html.

Figure 2-17

Figure 2-17 Weinre debug client console

  • + Share This
  • 🔖 Save To Your Account

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020