javascript - QUnit multiple scripts in one page but no interaction between them -
javascript - QUnit multiple scripts in one page but no interaction between them -
i'm new unit testing (this first day working qunit , i've never worked other testng scheme before), , i'm bit unclear on how test stuff multiple script files in 1 qunit page without letting scripts interact each other. mean is, say, if have script1.js
, , calls hello()
, , hello()
defined in script2.js
, how can run unit test on script1.js
create sure calls hello()
, mock output of hello()
it's true unit test, , run script2.js
's hello()
.
basically, how supposed hide 1 script's global variables , functions script in single qunit page?
this depends exclusively on how various script files organized scheme whole. if using angular, example, able inject dependencies when include module in script file. there tools mocking out things , "spying" on function calls such sinon, still depends heavily on how code organized.
for sake of argument, let's 2 files so, , we'll ignore design pattern (although should considering that)...
// file a: window.greeting = function() { var world = hello(); homecoming 'hello ' + world; } // file b: window.hello = function() { // perchance lots of code determine return... var value = 'foobar'; homecoming value; }
the hello()
function homecoming other value based on state of system, user input, etc. our case doesn't, , want mock out file b's code don't have test doing, gives string. we (and should) proper mocking/dependency injection library. however, give sense of minimal setup do, , see general approach, here's our qunit test file:
var _hello; qunit.module('file a', { setup: function() { _hello = window.hello; // hold onto old value // mock out hello() window.hello = function() { window.hello.called++; // track calls homecoming 'world'; // homecoming our static value } window.hello.called = 0; }, teardown: function() { // set old 1 window.hello = _hello || window.hello; } }); qunit.test('ensure greeting correct', function(assert) { var result = greeting(); assert.equal(window.hello.called, 1, 'hello should called once'); assert.equal(result, 'hello world', 'the greeting phone call should "hello world"'); });
and if want see running, here jsfiddle you. said, simple illustration show how could this, should proper code organization (think amd modules, require, angular, ember, things this) , proper mocking library.
javascript unit-testing global-variables qunit atomicity
Comments
Post a Comment