Search code examples
javascriptcoffeescriptphantomjscasperjsheadless

Headless JS site testing with test for each page


I'm trying to write headless integration tests for every page on my site in CoffeeScript/Javascript and run them in one command. I've tried using casperjs but I keep running into issues When attempting to run more than one test suite in a loop of requests.

Ideally I'd like to do something like this:

for page in ['/products','/about', '/contact']
   open(page, ->
       require("tests/#{page}/test.coffee").execute()

Where the test file looks something like:

exports.execute ->
    test.assert(pageTitleIs('about us'))

So that I could keep tests for each page in separate files, but run them all heedlessly with one command.


Solution

  • casper.thenOpen( url, ->
      @CurrentUrl = url
      @currentRoute = route
      @test.currentSuite = @test.running = @test.started = false # Hack. If we don't do this and a test fails, no tests after it will be executed
      @test.info("Testing #{urlPath}");
      path = currentDirectory+'/root'+route;
      if(fs.isDirectory(path))
        for file in fs.list(path)
          if(file.indexOf('.spec')!=-1)
            @echo 'executing file: ' + path + '/'+ file
            @test.exec(path + '/'+ file);
      @test.exec currentDirectory+"/smoke.test.js"
      @waitFor ->
        if test_done #Hack. If we don't do this, new tests will start before old ones finished.
          return true
        test_done = false
    )
    

    This is the solution I came up with, where smoke.test.js gets executed for every page. It's pretty hacky and I've run into many issues related to the scope of the tests, but it works.