Giter Club home page Giter Club logo

grunt-saucelabs's Introduction

grunt-saucelabs

Build Status Selenium Test Status

Selenium Test Status

Dependency Status devDependency Status

A Grunt task for running QUnit, Jasmine, Mocha, YUI tests, or any framework using Sauce Labs' Cloudified Browsers.

Grunt is a task-based command line build tool for JavaScript projects, based on nodejs. QUnit is a powerful, easy-to-use JavaScript unit test suite used by the jQuery, jQuery UI and jQuery Mobile projects and is capable of testing any generic JavaScript code, including itself! Mocha is a JavaScript test framework for running serial asynchronous tests. YUI Test is a browser-based testing framework from Yahoo!. Sauce Labs offers browser environments on the cloud for testing code.

About the tool

The grunt-contrib-qunit task runs QUnit based test suites on PhantomJS. The saucelabs-qunit task is very similar but runs the test suites on the cloudified browser environment provided by Sauce Labs. This ensures that subject of the test runs across different browser environment. The task also uses Sauce Connect to establish a tunnel between Sauce Labs browsers and the machine running Grunt to load local pages. This is typically useful for testing pages on localhost that are not publicly accessible on the internet. The saucelabs-jasmine runs Jasmine tests in the Sauce Labs browser. The saucelabs-jasmine task requires jasmine-1.3.0. There are also saucelabs-mocha and saucelabs-yui tasks that let you run your Mocha and YUI tests on Sauce Labs cloudified browser environment.

Usage

This task is available as a node package and can be installed as npm install grunt-saucelabs. It can also be included as a devDependency in package.json in your node project.

To use the task in grunt.js, load the npmTask.

grunt.loadNpmTasks('grunt-saucelabs');

In the grunt.initConfig, add the configuration that looks like the following

'saucelabs-qunit': {
  all: {
      options: {
      username: 'saucelabs-user-name', // if not provided it'll default to ENV SAUCE_USERNAME (if applicable)
      key: 'saucelabs-key', // if not provided it'll default to ENV SAUCE_ACCESS_KEY (if applicable)
      urls: ['array of URLs for unit test pages'],
      build: process.env.CI_BUILD_NUMBER,
      tunneled: 'true (default) / false; false if you choose to skip creating a Sauce connect tunnel.',
      tunnelTimeout: 'A numeric value indicating the time to wait before closing all tunnels',
      testInterval: 'Milliseconds between retries to check if the tests are completed',
      testname: 'Name of the test',
      tags: ['Array of tags'],
      browsers: [{
        browserName: 'firefox',
		    version: '19',
		    platform: 'XP'
      }],
      onTestComplete: function(result){
        // Called after a unit test is done, per page, per browser
        // 'result' param is the object returned by the test framework's reporter

        // Returning true or false, passes or fails the test
        // Returning undefined does not alter the test result

        // For async return, call
        var done = this.async();
        setTimeout(function(){
          // Return to this test after 1000 milliseconds
          done(/*true or false changes the test result, undefined does not alter the result*/);
        }, 1000);
      }
    }
  }
}

The configuration of saucelabs-jasmine, saucelabs-mocha, saucelabs-yui, and saucelabs-custom are exactly the same. Note the options object inside a grunt target. This was introduced in grunt-saucelabs-* version 4.0.0 to be compatible with [email protected]

The parameters are

  • username : The Sauce Labs username that will be used to connect to the servers. Required
  • key : The Sauce Labs secret key. Since this is a secret, this should not be checked into the source code and may be available as an environment variable. Grunt can access this using process.env.saucekey. Required
  • urls: An array or URLs that will be loaded in the browsers, one after another. Since SauceConnect is used, these URLs can also be localhost URLs that are available using the server task from grunt. Required
  • tunneled: Defaults to true; Won't launch a Sauce Connect tunnel if set to false. Optional
  • testname: The name of this test, displayed on the Sauce Labs dashboard. Optional
  • build: The build number for this test. Optional
  • tags: An array of tags displayed for this test on the Sauce Labs dashboard. This can be the commit number, branch name, etc, that can be obtained from grunt. Optional
  • browsers: An array of objects representing the various browsers on which this test should run. Optional
  • testInterval : Number of milliseconds between each retry to see if a test is completed or not (default: 5000). Optional
  • onTestComplete : A callback that is called every time a unit test for a page is complete. Runs per page, per browser configuration. Receives a 'result' argument which is the javascript object exposed to sauce labs. A true or false return value passes or fails the test, undefined return value does not alter the result of the test. For async results, call this.async() in the function. The return of this.async() is a function that should be called once the async action is completed. Optional

A typical test task running from Grunt could look like grunt.registerTask('test', ['server', 'qunit', 'saucelabs-qunit']); This starts a server and then runs the QUnit tests first on PhantomJS and then using the Sauce Labs browsers.

Exposing Test Results to the Sauce Labs API

Since this project uses the Sauce Labs js unit test API, the servers at Sauce Labs need a way to get the results of your test. Follow the instructions below to assure that the results of your tests are delivered properly.

Test result details with Jasmine

You can make Job Details pages more informative on Sauce by providing more data with each test. You will get info about each test run inside your suite directly on Sauce pages.

Jasmine detailed results

You can do that by using Jasmine JS Reporter that will let saucelabs-jasmine task provide in-depth data about each test as a JSON object.

All you need to do is to include the new jasmine-jsreporter reporter to the page running Jasmine tests by adding new script in header:

<script src="path/to/jasmine-jsreporter.js" type="text/javascript"></script>

and telling Jasmine to use it:

jasmineEnv.addReporter(new jasmine.JSReporter());

Test result details with QUnit

Add the following to your QUnit test specification

var log = [];
var testName;

QUnit.done(function (test_results) {
  var tests = [];
  for(var i = 0, len = log.length; i < len; i++) {
    var details = log[i];
    tests.push({
      name: details.name,
      result: details.result,
      expected: details.expected,
      actual: details.actual,
      source: details.source
    });
  }
  test_results.tests = tests;

  window.global_test_results = test_results;
});
QUnit.testStart(function(testDetails){
  QUnit.log = function(details){
    if (!details.result) {
      details.name = testDetails.name;
      log.push(details);
    }
  };
});

Test result details with mocha

Add the following to the mocha test page html. Make sure you remove any calls to mocha.checkLeaks() or add mochaResults to the list of globals.

<script>
  onload = function(){
    //mocha.checkLeaks();
    //mocha.globals(['foo']);
    var runner = mocha.run();

    var failedTests = [];
    runner.on('end', function(){
      window.mochaResults = runner.stats;
      window.mochaResults.reports = failedTests;
    });

    runner.on('fail', logFailure);

    function logFailure(test, err){

      var flattenTitles = function(test){
        var titles = [];
        while (test.parent.title){
          titles.push(test.parent.title);
          test = test.parent;
        }
        return titles.reverse();
      };

      failedTests.push({name: test.title, result: false, message: err.message, stack: err.stack, titles: flattenTitles(test) });
    };
  };
</script>

Test result details with YUI Test

There's nothing you have to do for YUI Tests! The js library already exposes window.YUITest.TestRunner.getResults()

Test result details with a custom framework

When you tests are finished, expose your tests results on window.global_test_results as explained in SauceLab's JS Unit Testing REST API Documentation

Examples

Some projects that use this task are as follows. You can take a look at their GruntFile.js for sample code

If you have a project that uses this plugin, please add it to this list and send a pull request.

Integration with a CI system

Grunt tasks are usually run alongside a continuous integration system. For example, when using Travis, adding the following lines in the package.json ensures that the task is installed with npm install is run. Registering Sauce Labs in test task using grunt.registerTask('test', ['server', 'saucelabs-qunit']); ensures that the CI environment runs the tests using npm test. To secure the Sauce Key, the CI environment can be configured to provide the key as an environment variable instead of specifying it file. CI Environments like Travis provide ways to add secure variables in the initial configuration. The IndexedDBShim is a project that uses this plugin in a CI environment. Look at the .travis.yml and the grunt.js for usage example.

Changelog

####5.1.1####

  • Qunit reporting code made ecma3 compatible
  • Qunit reporting code doesn't clober the .done() callback
  • Updated dependencies

####5.1.0####

  • Added custom framework
  • Updated the test reporting on example pages to provide details when tests fail

grunt-saucelabs's People

Contributors

sourishkrout avatar jonahss avatar axemclion avatar nschonni avatar bernii avatar cvrebert avatar nathanboktae avatar krinkle avatar hereandnow avatar smithclay avatar ginader avatar gmoon avatar jbowes avatar bitdeli-chef avatar ericdahl avatar jmreidy avatar alexstrat avatar proteamer avatar pwmckenna avatar jansepar avatar thanpolas avatar tscbp avatar spenceralger avatar

Watchers

James Cloos avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.