Karma as a jquery unit test runner

Source: Internet
Author: User

Karma as angular test runner appears, if you have used karma you must feel this very good JavaScript test runner. Simple and clean configuration file Karma.config.js, as well as some quick Config command for Karma init. and a complete suite of test kits, such as Html2js,coverage. For the angular unit test karma is an all-ecological test suite that provides a quick and simple way to build the entire test process.

This article attempts to use Karma as the jquery unit Test Runner. For the framework of DOM operations such as jquery, it is sometimes difficult to separate the view logic and the mock of external resources such as Ajax, so it is more difficult to implement TDD development for jquery programs.

Jasmime Test Kit

For the Jasmine test framework to address these issues there are two plug-ins jasmine-jquery and Jasmine-ajax.

Jasmine-jquery

Jasmine-jquery primarily solves the DOM elements required to load a test and builds a pre-environment for unit testing. Jasmine-jquery Loading Dom Method:

Jasmine.getfixtures (). Fixturespath = ' base path '; Loadfixtures (' myfixture.html '); Jasmine.getfixtures ( ). Load (...);

Here Loadfixtures need real Ajax to get HTML fixtures so we need to advance host HTML fixtures. Jasmine-jquery also frames some useful matchers, such as tobechecked, tobedisabled, Tobefocused,tobeindom ...

Jasmine-ajax

Jasmine-ajax is a mock framework for general Ajax testing, which implements mocks from the underlying xmlhttprequest. So let's make it easy to implement the $.ajax,$.get...mock for jquery. Such as

Beforeeach (function() {Jasmine. Ajax.requests.when=function(URL) {return  This. Filter ("/jquery/ajax") [0];    }; Jasmine. Ajax.install ();}); It ("jquery Ajax success with GetResponse",function() {    varresult; $.get ("/jquery/ajax"). Success (function(data) {result=data;    }); Jasmine. Ajax.requests.when ("/jquery/ajax"). Response ({"Status": 200,      "ContentType": ' Text/plain ',      "ResponseText": ' Data from mock Ajax '    }); Expect (result). Toequal (' Data from mock Ajax ');}); Aftereach (function() {Jasmine. Ajax.uninstall ();});

For Jasmine-ajax it is necessary to Jasmine before implementing a mock. Ajax.install (), and Jasmine is required after the test is complete. Ajax.uninstall (); Jasmine-ajax will mock all Ajax after install, so if there is a need for real Ajax to be done before install, such as jasmine-jquery load view Loadfixtures.

Using Karma Runner

We have learned about the two frameworks jasmine-jquery and jasmine-ajax of the Jasmine test, so using karma as a runner, the problem we need to solve is to integrate them with karma.

So it is divided into the following steps: 1:karma introduces Jasmine-jquery and Jasmine-ajax (can be used Bowerinstall) 2:host test HTML fixtures. 3: Load HTML fixtures with install Ajax before.

The Karma provides the pattern mode for the host file, so the karma is configured as:

files: [    {      ' view/**/*.html ',      true,      false,       true     },    ' Bower_components/jquery/dist/jquery.js ',    ' bower_components/jasmine-jquery/lib/ Jasmine-jquery.js ',    ' bower_components/jasmine-ajax/lib/mock-ajax.js ',    ' src/*. JS ',    ' test/*.js '],

It is important to note that the karma comes with a low jasmine version, so we need NPM install [email protected] to get the latest Karma-jasmine plugin.

We can complete the configuration of the karma, we can simply test our configuration: demo on GitHub.

To test the HTML fixtures load:

function () {  Beforeeach()    {= ' base/view/';    Loadfixtures ("index.html");  });  It (function() {    expect ($ ("H2")). Tobeindom ();    Expect ($ ("H2")). Tocontaintext ("This is index page");  } )

Test mock Ajax:

Describe (' Console HTML content ',function() {Beforeeach (function() {Jasmine. Ajax.requests.when=function(URL) {return  This. Filter ("/jquery/ajax") [0];     }; Jasmine. Ajax.install ();  }); It (' Index HTML ',function() {Expect ($ ("H2") . Tobeindom (); Expect ($ ("H2"). Tocontaintext ("This is Index page"));  }); It ("Ajax Mock",function() {    varDonefn = Jasmine.createspy ("Success"); varXHR =NewXMLHttpRequest (); Xhr.onreadystatechange=function(args) {if( This. ReadyState = = This. Done) {Donefn ( This. responsetext);    }    }; Xhr.open ("GET", "/some/cool/url");    Xhr.send (); Expect (Jasmine. Ajax.requests.mostRecent (). url). toBe ('/some/cool/url ');    Expect (DONEFN). not.tohavebeencalled (); Jasmine. Ajax.requests.mostRecent (). Response ({"Status": 200,      "ContentType": ' Text/plain ',      "ResponseText": ' Awesome response '    }); Expect (DONEFN). Tohavebeencalledwith (' Awesome response ');  }); It ("jquery Ajax success with GetResponse",function() {    varresult; GetResponse (). Then (function(data) {result=data;    }); Jasmine. Ajax.requests.when ("/jquery/ajax"). Response ({"Status": 200,      "ContentType": ' Text/plain ',      "ResponseText": ' Data from mock Ajax '    }); Expect (result). Toequal (' Data from mock Ajax ');  }); It ("JQuery Ajax Error",function() {    varstatus; $.get ("/jquery/ajax"). Error (function(response) {Status=Response.Status;    }); Jasmine. Ajax.requests.when ("/jquery/ajax"). Response ({"Status": 400    }); Expect (status). Toequal (400);  }); Aftereach (function() {Jasmine.  Ajax.uninstall ();      });}) 

See demo on GitHub for more information.

Karma as a jquery unit test runner

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.