Evolving Bits

JavaScript. iOS.

Testing Parse.com Cloud Code Using Q Promises: Part 1

I’ve been playing with Parse.com Cloud Code, and wanted to write more code offline so I didn’t have to keep pushing to the cloud, plus wanted to use Test Driven Development.

I also had seen their blog post What’s so great about JavaScript Promises? and decided that was the best way to go for handling async logic.

For testing and mocking, I discovered the Q promise library which is fantastic. For a great intro listen to the 037 JSJ Promises with Domenic Denicola and Kris Kowal podcast and see Q Getting Started and Tutorial.

The problem I ran into was that the Parse.com promise library handles error-handling differently than the Promises/A+ spec (instead it follows jQuery’s implementation) so then started trying to create a mock of a Parse.com promise, but this was a bit tricky and I wasn’t happy with result.

Then I finally had the thought to replace the Parse.com promise implementation with Q. That way I could implement my Cloud Code with Q and also write my tests with Q.

Here’s an initial experiment of using Q with Parse.com Cloud Code.

How to run: I just created a new Cloud Code project with the Parse command-line tool parse new and then grabbed q.js via an npm install q and copied q.js into the ./cloud directory.

Here’s the code on gist.github.com

One Letter Repository Status for Git, Mercurial and Subversion

These days we’re using a variety of version control systems and switching between them regularly.

My most used command is checking my working directory status, so I’ve distilled it down to a one-letter shortcut that determines which type of repository I’m in, then does an appropriate status for that system.

I just setup an alias like this:

s='~/s/s.sh'

So just type s and don’t worry about which version control you’re in.

Here’s the code on gist.github.com

Testing JavaScript Code Running Google Closure Library Using Mocha and PhantomJS (or Jasmine)

Here are several options for setting up JavaScript unit testing for code built with the Google Closure Library, albeit these options are helpful for testing a wide variety of JavaScript projects.

Google Closure Library is self-described as a “broad, well-tested, modular, and cross-browser JavaScript library.”

We’re using the LimeJS HTML5 game framework, which is built on this library.

Our Contestants

1. Headless testing with Jasmine 1.2

Jasmine works well. There are two approaches you can use: an HTML runner with jasmine.js, or the Ruby-based runner. Originally we were hoping to take the same approach as the Ruby-runner (with all batteries included, including easy headless testing) but using Mocha and Node.js instead to be on a full JavaScript stack. Though we ended up having to go to an HTML runner + mocha.js to get the DOM testing to work, in scenario 3 below.

In hindsight, by ending up with the HTML + JS approach in scenario 3, Jasmine and Mocha + PhantomJS are very similar approaches.

2. Mocha testing on Node.js

Mocha testing on Node.js works well (easy setup, no html test runner required), but I wasn’t able to get headless DOM working. If your tests don’t require DOM, this is a good way to go. One issue: It takes more effort to debug tests with breakpoints because the code is running on node.js. In the other scenarios, you can just add a debugger line and debug the tests in the browser.

3. Headless testing with Mocha and PhantomJS

Our winner: Headless testing with Mocha and PhantomJS via mocha-phantomjs allows us to use JavaScript tooling, headless DOM testing and a nice Jasmine BDD style for writing tests.

4. Testing with the Google Closure Library testing framework

You can use the Google Closure Library testing framework, which is more of a traditional JUnit style framework and not a BDD-style framework like Jasmine or Mocha. Please check out the Closure documentation for more info.

Let’s Get Testing

Here’s how each can be setup.

Assume you keep your tests in a my-project/spec folder and your code is under a peer my-project/scripts folder. Assume all test-related files discussed below are in the ./spec folder and that tests are kicked off via a script in that folder.

1. Jasmine

This is a personal favorite. It has all batteries included and doesn’t need a separate HTML runner for DOM testing if using the Ruby Gem. We liked this approach, and tried to do it with Mocha + node.js (to get the same features as the Ruby Gem, but on a JavaScript stack) though ultimately went with Scenario 3 below.

For general setup of headless Jasmine testing, see my jasmine-headless-boilerplate repository.

Once setup, to tailor for Google Closure Library, in javascripts/support/jasmine.yml (setup by default with jasmine init) add your project’s base.js and generated deps.js file to ./spec.

src_files:
    - scripts/libs/closure/closure/goog/base.js
    - scripts/deps.js

You can then just create a standard Jasmine test file with goog.require() statements at the top to bring in the module dependencies:

goog.require('the.module.I.am.testing');
goog.require('a.dependency');

describe("the.module.I.am.testing", function () {

});

2. Mocha Testing on Node.js

After setting up node.js and npm, you can create a package.json file to make it easy to setup all the dependencies by just running npm install in your ./spec folder.

If you have a script that kicks off the tests, you can optionally add that to the “scripts > tests” key like seen below so that you can just run npm test.

Also, you’ll need to use the nclosure library to allow node.js to bring in dependencies via goog.require().

In ./spec create 3 files:

  • closure.json to tell nclosure library where your files are

  • package.json to setup all your node.js dependencies

  • a run script

Here are examples:

closure.json

{
  additionalDeps:['../scripts/deps.js'],
  closureBasePath:'/this/has/to/be/an/absolute/path/in/my/experience/scripts/libs/closure/'
}

It took some time to figure out the right file paths. Basically:

  • “additionalDeps” should be a relative path from where you’re running the script that runs the tests. If you’re running tests from a ./spec folder, and the code lives in a peer (to ./spec) ../scripts folder, use the example above.

  • However the closureBasePath only worked as an absolute path, plus you leave off the trailing /closure/goog (since often closure is in a lib/closure/closure/goog directory structure).

I assume this could be fixed with either a patch to nclosure or maybe I wasn’t doing something correctly. I also tried setting this as a parameter to the actual require('nclosure').nclosure(); call at the top of the tests, but no difference. This would need to be solved to make it easy for a team to run tests locally.

package.json

{
  "name": "our-test-framework",
  "version": "0.0.0",
  "description": "## Unit Tests",
  "main": "index.js",
  "scripts": {
    "test": "sh runtests.sh"
  },
  "repository": "",
  "author": "",
  "license": "BSD",
  "dependencies": {
      "chai":"~1.3",
      "sinon": "~1.5",
      "nclosure": "~0.4",
      "mocha": "~1.6"
    }
}

runtests.sh

#!/bin/sh
./node_modules/.bin/mocha --recursive --timeout 10000 --reporter spec your/folder/to/your/specs

Here’s an example test file:

require('nclosure').nclosure();

goog.require('my.module.goes.here');
goog.require('one.of.your.dependencies');

describe("my.module.goes.here test", function () {

});

3. Mocha Testing on PhantomJS (node.js not required)

This is the current winner for our specific needs. It’s mainly JavaScript based, runs headless DOM tests, and supports a nice BDD syntax.

This has some additional dependencies beyond the setup above:

  • Install PhantomJS, which on OSX is as easy as brew install phantomjs via Homebrew.

  • Bring down mocha-phantomjs.coffee and the mocha-phantomjs folder from mocha-phantomjs and put those in your ./spec folder.

  • Bring in dependencies mocha.js and mocha.css from root of mocha repository

  • Bring in third-party libraries like expect.js and sinon.js used by test runner HTML below. (We started with Chai’s “expect” assertion framework, but the assertion code didn’t nicely pass linting, so went with the very similar expect.js)

Instead of using the ./mocha test runner, your run-script can call each test like so:

phantomjs mocha-phantomjs.coffee javascripts/mycontroller_spec.html

In addition to your test js file, you need an html file test runner to setup DOM for your tests.

Here’s an example of mycontroller_spec.html:

<html>
  <head>
    <title>Unit Tests</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../../node_modules/mocha/mocha.css" />
  </head>
  <body>
    <div id="mocha"></div>
    <script src="../../../../scripts/libs/closure/closure/goog/base.js"></script>
    <script src="../../../../scripts/deps.js"></script>
    <script src="../../../javascripts/support/sinon-1.4.2.js"></script>
    <script src="../../../javascripts/support/mocha.js"></script>
    <script src="../../../javascripts/support/expect.js"></script>
    <script>
      mocha.ui('bdd'); 
      mocha.reporter('html');
    </script>
    <script src="mycontroller_spec.js"></script>
    <script>
      if (window.mochaPhantomJS) {
        mochaPhantomJS.run();
      } else {
        mocha.run();
      }
    </script>
  </body>
</html>

The mycontroller_spec.js test file doesn’t require any special code, just using the normal goog.require():

goog.require('my.module.goes.here');
goog.require('one.of.your.dependencies');

describe("my.module.goes.here test", function () {

});

Other thoughts and ideas

  • For tests requiring DOM: Is it possible to substitute zombie.js instead of phantomjs? The main reason is that then the whole stack could be in node.js and has fewer dependencies (since it wouldn’t require phantomjs and mocha-phantomjs).

  • Selenium is another option for testing code against DOM on real browsers.

References To Bookmark

Favorite Tuesday Talks at 360iDev 2012

Here were four talks I enjoyed, plus Game Jam.

Poking a Hole in the Sandbox, using URLs on iOS

      By Greg Pierce, @agiletortoise, Slides

  • Lightweight local messaging between apps.

  • A way to test if certain apps are installed, great for cross promotion too.

  • A protocol for iOS interapp communication http://x-callback-url.com

It’s All in the Tools

      By Nathan Eror, @neror, Slides

  • How to wield Xcode with keyboard shortcuts (Jump bar: ^[1-6], learn keys from top menu items View and Navigation), Behaviors, breakpoints (logging, sounds, shell scripts, llvm allows breakpoints without restarting app), and powerful lldb debugging (formatters, summarizers, python integration, .lldbinit).

  • Uses make to automating (things like removing sqlite databases), supports autocompletion. See his blog entry on this.

  • Mountain Lion has Python bindings for Cocoa – see a nice Quartz example in his slides. This was news to me, and after Googling around didn’t find much into about this.

Creating Container View Controllers

      By Bob McCune, @bobmccune

  • These are now easier to create in iOS 5+. A subtle API for adding/removing child controllers, get children, new callbacks. Only use this API within your container. Avoid common mistakes: Outside callers (since invalidates containers view of the world), disobedient children, meddling parents (let children be children)

  • Demo code is here: https://github.com/tapharmonic

Galcon

      By Phil Hassey, @philhassey

  • Phil following his gaming development passions with Galcon and other games, including his new Dynamite Jack.

Game Jam (7pm to 7am)

  • Phil Hassey’s Galcon talk motivated me to give Game Jam a try.

  • I enjoyed this for several hours before drinking and socializing set in.

  • Had fun with cocos2d and box2d.

Favorite Monday Talks at 360iDev 2012

My favorite talks are the developer-heavy ones. Here were three I enjoyed today.

Advanced Debugging Code (on Sunday)

      By Kendall Helmstetter Gelner, @kendalldevdiary, Slides (pdf) and Sample Project on Github

  • This talk was chalk full of debugging goodness: logging, instruments, LLDB, breakpoints, ARC (less code == less to debug), Pony Debugger, Charles, Core Data.

Developing for Reuse

      By Andria Jensen, @andriajensen, slides: http://bit.ly/U3RA4V

  • Andria had a great presentation and her slides are very useful for best practices in modularizing code for Objective-C and Xcode.

  • This very topic was resonating with me last night (iOS Automated Testing: Refactored), and although she didn’t cover the unit testing pieces, she went way beyond the first step of git submodule modularization and went into Xcode workspaces, static libraries, bundles, and categories.

PhoneGap

      By Andrew Trice, @andytrice

  • Andrew is a great resource and has some interesting projects on Github such as app-UI, Lil-Doodle, Fresh-Food-Finder.

  • “What’s the difference between PhoneGap and Cordova?” They’re the same code base right now. Cordova is the open source project, and PhoneGap is Adobe’s distribution, and they own the PhoneGap name.

  • Some libraries he uses are Backbone.js, and Leaflet (“An Open-Source JavaScript Library for Mobile-Friendly Interactive Maps by CloudMade”)

  • He showed some good plugins, like second screen support (native PhoneGap code to support multiple screens). PhoneGap Plugins are nice since they give JavaScript access to anything you can do in the native layer, and there are many plugins that have already been developed.

  • Presentation Suggestion I have: Many of the PhoneGap examples are business apps (Apple Store, LinkedIn, BBC Olympics, Zombie Jombie, Wikipedia, Untappd, Bit Timer, US Census Browser) though there are JavaScript libraries out there (such as lime.js) that make PhoneGap a nice platform for gaming too.

“Stop it! That Hurts!” Common iOS Anti-Patterns

      By Carl Brown, @carlbrwn, slides: http://t.co/JRWPcd1B

  • His whole talk is great. Topics include Error handling, Asynchronous, Date, Security, Caching, View tagging, Core Data results, don’t mix read-only and read-write data.

  • He’s in Austin, home of SXSW Interactive where it “Looks like any idiot can make an App”, sees a lot of (bad) code

Suggestions

  • Read good code – and NOT these from Github Objective-C “Most Watched”: three20, asi-http-request, AFNetworking, facebook-ios-sdk, Restkit.

  • His “Rocket Engine” for Responsive Code (to make sure you’re not doing much on main thread): NSAssert(![NSThread isMainThread], @"BOOM");

  • Uses NMVC pattern (“N” for Network), essentially networking happens at the data layer and not throughout code.

  • Carl had some criticisms with RestKit, so I asked him more details after the talk. The criticism is more that Restkit tries to abstract what’s local and what’s remote, and it’s not always clear what’s happening. He turned me onto a nice recommendation: MagicalRecord which is a Category for Core Data that handles fetching of remote data and adding to Core Data.

Summary

  • Program sober and rested, if possible

  • Leave other language’s patterns at the door

  • Program idiomatically (“The specific grammatical, syntactic, and structural character of a given language.”)

  • Don’t fight the frameworks

iOS Automated Testing: Refactored

My mobile projects lately include various combinations of JavaScript and Objective-C. Usually either 100% native iOS, or JavaScript running on a native iOS (or Android) layer.

I also like to dabble with various projects, and am tired of the heavy weight of setting up new Xcode projects when I just want to experiment with some concepts. The JavaScript side is already much lighter.

I consider it heavy because:

  • I have various snippets strewn across projects, and

  • getting Xcode tests up and running sucks the life out of me when I just want to jump into some code. True, new Xcode projects do create boilerplate tests, but still requires setup for including other 3rd-party libraries like OCMock.

An example scenario:

  • Today I’m dabbling with geofencing in an app, but tomorrow I may want to use that code in a hybrid Cordova/PhoneGap app, Thursday I might want to refactor geofencing into something else.

I’m very happy with Jasmine for testing JavaScript, since it’s easy to setup and use. I created a jasmine-headless-boilerplate project that is a starting place for those wanting to setup and run Jasmine JavaScript tests with their projects, and also be able to run it headless on their CI server or on Travis CI.

The New Plan

So for my Objective-C code, I have formulated a plan to deal with both of these at once:

  • Modularization: I’m going to focus on moving code out of specific apps and into a personal library. I’ll then include that as a git submodule in any new project I begin, whether native or hybrid. I’ve been doing some of this modularization already by avoiding the impulse to add too much code directly into UIViewControllers, but rather putting code into custom classes that are then used by the UIViewController.

  • Testing: The personal library will also be housed in a bare bones Xcode project, which will only have unit tests and 3rd-party testing libraries (like OCMock), so that I can ensure that code is tested before it gets used in my projects.

When I’m done, I’ll have a versatile and well-tested library that I can quickly add to any project or experiment.

Here’s a Starter Project to play with: Enjoyable iOS Testing

Other Xcode Testing Starter Projects and Resources

I’m now looking around for bare bones Xcode starter projects to use:

  • Xcode-Templates looks interesting

  • Cedar looks even more interesting since it’s closely related to Jasmine and looks like it will blend well with my JavaScript work.

With Great JavaScript Comes Great Inspiration

I’d say the theme of Day Two at JSConf 2012 was inspiration, and was another great day of talks:

  • I think my favorite talk (best presentation, very pragmatic) was Jake Archibald’s “Application Cache” – why it’s useful and the potholes you’ll encounter while using it. You’ll want to watch this video.

  • The best demo for me was the presentation prior, Thomas Valletta’s “The Web Game Console”, where he talked about his experience developing his mobile game with HTML and JS. He wrote a Web Bowling game using HTML/JS on iOS as the controller, and a Node.js websocket server for displaying the bowling alley. The source is on Github (so you can setup your own server if you want) and if multiple people play at the same time it turns into “battle bowling” with multiple balls at the same time.

  • Project Bikeshed was a great demo too. Not only did its authors put on a great daily video series, but Bikeshed allows you to do many useful things such as importing Flash SWF files, automatically turning those into JavaScript and then allowing you to show, combine, manipulate, animate any of those elements and use them in your JavaScript projects. He demo’d an iPad JavaScript game that was powered by Bikeshed. You can also run Bikeshed on Node.js and send that to devices. With a one-line change, he showed running both scenarios.

  • Ok, another great demo was on Open Data in the B-Track by Daniel Beauchamp & Edward Ocampo-Gooding. They actually packed about 7 small presentations into one and described their process of organizing a city hack-a-thon around Open Data and building a lot of apps for free for the benefit of your city and your community. Very inspired.

  • The Node.js talk from Brian Ford inspired us with some interesting readings to check out (such as the “Thinking Fast and Slow” book) and the importance of leveraging communities outside of JavaScript, such as the experiences of the Ruby community. He then had many concerns about Node.js repeating concurrency mistakes that Ruby had made. Though I think I mainly left there with only some good book suggestions – it felt like it ended abruptly since there was no time for questions (since presentation went long) and no specific next steps on how to avoid said concerns.

  • One of the most inspirational talks was 19-year-old James Whelton’s “Changing the world one CoderDojo at a time”. CoderDojo is “a movement of free coding clubs for young people”. Check out their site for a lot of inspiration and how to start a club yourself. Also turns out that JavaScript has been a very accessible language to use – it requires no setup, is available everywhere, fun to work with, and can even land you a job down the road.

  • Jacob Thornton’s “Brûlons les musées” talk was also very entertaining, and you’ll need to see the video. He led up to the power of the JavaScript community getting together more specifically around creating specs/tests (versus primarily getting together around an implementation), which then offer flexibility and healthy competition when implementing libraries that meet those specs. His example was creating Hogan.js, which is some ways was a rewrite of Mustache.js. The improvements were possible by leveraging the Mustache tests. Then Mustache was able to make improvements. By using the specs, separate projects were able to code and optimize independently.

  • The final talk of the day was Rick Falkvinge’s talk about politics, the Pirate Party and inspiration on how to change the world. He told his story of how the Pirate Party has been able to make in-roads into mainstream politics, and what’s possible.

Green for Dinner

After the JSConf family photo, nine of us then went to a local vegetarian restaurant called Green which was amazing. The place was packed the whole time while the atmosphere was very easy going. They had a great variety of original and tasty foods.

Boot2Gecko Phone

In the evening, I finally had a chance to play with Mozilla’s Boot2Gecko phone and built a simple app. In Accelo the JSConf logo floats around the screen and moves as you tilt the phone.

Development was fairly smooth and I was able to install my app as part of the Gaia update/install process, but didn’t have luck yet setting it up to install as a stand-alone app.

Albeit since the app is solely HTML/CSS/JS it works just fine by visiting the site http://accelo.evolvingbits.com/accelo/ on the Boot2Gecko phone (or even works on my Macbook Pro which apparently sends accelerometer events). However when viewing on iOS, the accelerometer events seem to be reversed, so not sure which implementation is off.

Thank you

Thanks JSConf for another great year of new friends, bull-riding, great talks, tasty food and inspiration. I will miss the sunshine and the playtime, but excited to jump into the all new tech-wonders that I can use for my web and mobile projects back in Seattle. The Firesky Resort in Scottsdale was a perfect conference location, and I was also very happy with my stay next door at Chaparral Suites.

Also a big thank you to my company Saltbox.com who have sponsored me to attend JSConf this year! We’re developers of an online communication and learning application that allows Sales organizations to keep a pulse on what happening with their products, their customers and their competitors.

JSConf 2012: Play

On my flight to JSConf, the Southwest Airlines magazine kicked off the topic of Play in Its called Play

This theme continued throughout JSConf 2012’s Day One.

Just a few things to play with:

  • Registration included getting an NFC Poken, taking pictures with guns and cowboy gear, and a bag of sponsor loot.

  • All attendees were given the first public Boot2Gecko phones from Mozilla with a challenge to hack it and build apps by conference end.

  • Stephan Herhut showed us the possibilities with true parallel programming and JavaScript using Intel RiverTail.

  • Paul Irish showed us the latest in JavaScript tooling. His presentation.

  • Max Shawabkeh walked us through repl.it which runs 17 languages natively in JavaScript, including Python and Ruby. This is a great environment for new students to programming (since the only dependency is a web browser), or people wanting to play with compiler technology.

  • Remy Sharp talked about using JavaScript to “Build Anything” and gave a list of things he’s like to see browsers do, such as real-time notifications, strong desktop integration, direct access to hardware, ability to local install a JavaScript app, “go naked” (no browser chrome visible). He also talked about things we should be using today, such as web storage instead of cookies, using HTML5 tags for web form validation (i.e. instead of a crazy client-side email regular expression, use <input type=email>), History API, AppCache manifest for performance (since just relying on browser cache may mean your files disappear after cache fills up), EventSource particularly for mainly server-to-client pushes (in addition to websockets), Drag and Drop.

  • David Nolen talked directly about the importance of Play and how ClosureScript was that playground for him. He was also inspired by the book ”The Reasoned Schemer”.

  • Dan Ingalls, “principal architect, designer and implementor of five generations of Smalltalk environments” took us through Lively Kernel which you need to see in action. It “provides a complete platform for web applications, including dynamic graphics, network access, and development tools” all in the browser.

  • Attendees left Day One with new cowboy hats, and many rode the bull later that night at Saddle Ranch.

Thanks NotConf for a Great JSConf 2012 Pre-conference

Arriving PHX was flawless, the Twilio-sponsored shuttle was there to pick me up from the airport.

After checking-in, it was sunny and mid-70s as a few of us awaited for a friendly volunteer-sponsored shuttle to whisk us over to NotConf in fine style.

This one day event went off without a hitch and was a lot of fun.

We arrived to free food, free local beer, t-shirts, sunshine, friendly faces – and of course JavaScript. 30-min talks leap frogged 30 min demos.

Best talk

I was only there the last half of the day, so my favorite talk was Pamela Fox’s (she also won best costume) “Why ternary operators make me want to kick someone in the nuts: AKA code readability.” She highlighted that most JavaScript developers are users of other people (library) code, and had many good points about what to do to make users lives much easier by making the code more approachable:

  • Documentation – but not too much (such as having two sets of docs that makes it unclear which are the definitive ones) and using doc generation tools to make docs part of the process and not manual

  • Make debugging headache free (by being clear, using less “elite” code, no crazy ternary operators) since at some point users will need to debug in there. Use tools like jshint to keep your code consistent. Also, although you can write javascript without semi-colons, this is not what most users expect and can lead to pain for potential contributors and users.

  • Make it easy to contribute to the (library) project. A lot of dependencies for running tests could be one barrier.

Favorite Demo

My favorite demo was deployd.com who had wired up an iRobot and a maze, and attendees could create a program that navigated the robot through it, complete with leaderboard. This demonstrated their cool “instant backend” for software developers and tinkerers to easily create a RESTful backend with no code – which in this case was then downloaded to a robot. Their business card says it all with “Join the Backend Liberation Movement”.

Thank you

The closing event was of course outside, where we all wound down with beer, nice conversations, and a local musician who was playing for us in the courtyard. My pale Seattle skin even gained some color and was happy to absorb all that natural Vitamin D.

Thanks to the organizers of NotConf.com – it was an impressive one-day conference and a great start to JSConf 2012.