Quick Autotest for NodeUnit and Node.Js on Mac OSX


Very simple way to get Autotesting in Node.js.

What is Autotesting? Simply put, it runs your unit tests automatically whenever you save a relevant file within your project.

  • First, install GROWL and GROWLNotify for Mac (http://growl.info/)
  • Next we want to install the ‘watchr’ gem…
    gem install watchr
    
  • Next create a file called autotest.watchr in the root of your Node.js project with the following ruby script…
    def run_all_tests
      print 'clear'
      puts "Tests run #{Time.now.strftime('%Y-%m-%d %H:%M:%S')}"
      result_text = `nodeunit [TESTFOLDER]`
      result = result_text.include? 'failed'
      if result
    	`growlnotify -m 'Unit Tests Failed' Node Unit`
      else
    	`growlnotify -m 'All Unit Tests Passed' Node Unit`
      end
    end
    
    run_all_tests
    watch("(test|lib)(/.*)+.js") { |m| run_all_tests }
    
    @interrupted = false
    
    # Ctrl-C
    Signal.trap "INT" do
      if @interrupted
        abort("\n")
      else
        puts "Interrupt a second time to quit"
        @interrupted = true
        Kernel.sleep 1.5
    
        run_all_tests
        @interrupted = false
      end
    end
    

    Do not change the ` chars. This actually tells Ruby to output the text directly to the console (for those that didn’t know)

  • Replace [TESTFOLDER] in file above with your test folder
  • Run watchr..
    watchr autotest.watchr
    

Thats it! Now simply edit a .js file in your solution and the tests will run automatically and inform you of failures.

Feel free to add your favourite icons for failures and passes to GROWL. If you do, please send us an updated script ;)