Thursday, September 29, 2011

JavaScript testing with closure jsunit and Webdriver

I recently set about looking into JavaScript testing frameworks.

In the end it came down to comparing Pivotal Labs' Jasmine framework to Closure's JSUnit wrapper. I really wanted to use Jasmine, but had peculiar problems that may be due to my own code or my assumptions about how to use it. Stack traces were sometimes less than useful (except on Safari) in Jasmine and then I got stuck trying to load fixtures from files and having race conditions. Jasmine seemed to load and execute extremely fast, almost too fast, but anyhow, I couldn't get things working so I went back to the tried and true.

I should also maybe mention that I'm using Sinon.js as much as possible and *really* enjoying how it works.

One particularly nice thing about closure's test runner is that it's instrumented for Webdriver integration. I'm not a Java nut, so I wrote my webdriver test in python and wanted to share the code here because I had some trouble finding references online to working code.

Worth noting that I downloaded the chromedriver binary and actually checked it in next to my test but also have this code working with the Firefox driver as well as the iphone simulator, using iWebDriver (which is totally freakin cool).

Just sharing below in case anyone finds it interesting or useful.


__author__ = 'Lindsey Simon'

import os
import time

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys

The chromedriver binary (mac) will be able to run the tests.
For targeting an iphone simulator, one needs to follow the instructions (we used iOS Latest).
Then you can start the simulator outside of XCode and leave the iWebTest
app running, targeting localhost in the webdriver.Remote below.

TEST_PATH = os.path.dirname(os.path.abspath(__file__))

drivers = (
    # webdriver.Remote(command_executor='http://localhost:3001/hub',
    #                  desired_capabilities={'browserName': 'iphone'}),
    # webdriver.Firefox(),
    webdriver.Chrome(TEST_PATH + '/external/chromedriver')

for driver in drivers:
    # These are test pages which include closure + jsunit to drive them.
    test_pages = ('test1.html', 'test2.html')
    test_results = []

    for test_page in test_pages:
        url = 'file://%s/%s' % (TEST_PATH, test_page)
        # Freakin cool.
        while not driver.execute_script('return G_testRunner.isFinished()'):

        print '%s' % driver.execute_script(
            'return G_testRunner.getReport()')

            driver.execute_script('return G_testRunner.isSuccess()'))

    for test_result in test_results:
        assert test_result


No comments: