Move Webstore URL concepts to //extensions and out
[chromium-blink-merge.git] / chrome / test / data / webui / test_api.js
blob460495c985d548e9e1cdbcfaf3f499c26060c066
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 /**
6 * @fileoverview Library providing basic test framework functionality.
7 */
9 /**
10 * Namespace for |Test|.
11 * @type {Object}
13 var testing = {};
14 (function(exports) {
15 /**
16 * Holds the original version of the |chrome| object.
18 var originalChrome = null;
20 /**
21 * Hold the currentTestCase across between preLoad and run.
22 * @type {TestCase}
24 var currentTestCase = null;
26 /**
27 * The string representation of the currently running test function.
28 * @type {?string}
30 var currentTestFunction = null;
32 /**
33 * The arguments of the currently running test.
34 * @type {Array}
36 var currentTestArguments = [];
38 /**
39 * This class will be exported as testing.Test, and is provided to hold the
40 * fixture's configuration and callback methods for the various phases of
41 * invoking a test. It is called "Test" rather than TestFixture to roughly
42 * mimic the gtest's class names.
43 * @constructor
45 function Test() {};
47 Test.prototype = {
48 /**
49 * The name of the test.
51 name: null,
53 /**
54 * When set to a string value representing a url, generate BrowsePreload
55 * call, which will browse to the url and call fixture.preLoad of the
56 * currentTestCase.
57 * @type {string}
59 browsePreload: null,
61 /**
62 * When set to a string value representing an html page in the test
63 * directory, generate BrowsePrintPreload call, which will browse to a url
64 * representing the file, cause print, and call fixture.preLoad of the
65 * currentTestCase.
66 * @type {string}
68 browsePrintPreload: null,
70 /**
71 * When set to a function, will be called in the context of the test
72 * generation inside the function, after AddLibrary calls and before
73 * generated C++.
74 * @type {function(string,string)}
76 testGenPreamble: null,
78 /**
79 * When set to a function, will be called in the context of the test
80 * generation inside the function, and after any generated C++.
81 * @type {function(string,string)}
83 testGenPostamble: null,
85 /**
86 * When set to a non-null string, auto-generate typedef before generating
87 * TEST*: {@code typedef typedefCppFixture testFixture}.
88 * @type {string}
90 typedefCppFixture: 'WebUIBrowserTest',
92 /**
93 * This should be initialized by the test fixture and can be referenced
94 * during the test run. It holds any mocked handler methods.
95 * @type {?Mock4JS.Mock}
97 mockHandler: null,
99 /**
100 * This should be initialized by the test fixture and can be referenced
101 * during the test run. It holds any mocked global functions.
102 * @type {?Mock4JS.Mock}
104 mockGlobals: null,
107 * Value is passed through call to C++ RunJavascriptF to invoke this test.
108 * @type {boolean}
110 isAsync: false,
113 * True when the test is expected to fail for testing the test framework.
114 * @type {boolean}
116 testShouldFail: false,
119 * Extra libraries to add before loading this test file.
120 * @type {Array.<string>}
122 extraLibraries: [],
125 * Extra libraries to add before loading this test file.
126 * This list is in the form of Closure library style object
127 * names. To support this, a closure deps.js file must
128 * be specified when generating the test C++ source.
129 * The specified libraries will be included with their transitive
130 * dependencies according to the deps file.
131 * @type {Array.<string>}
133 closureModuleDeps: [],
136 * Whether to run the accessibility checks.
137 * @type {boolean}
139 runAccessibilityChecks: true,
142 * Configuration for the accessibility audit.
143 * @type {axs.AuditConfiguration}
145 accessibilityAuditConfig_: null,
148 * Returns the configuration for the accessibility audit, creating it
149 * on-demand.
150 * @return {axs.AuditConfiguration}
152 get accessibilityAuditConfig() {
153 if (!this.accessibilityAuditConfig_) {
154 this.accessibilityAuditConfig_ = new axs.AuditConfiguration();
156 this.accessibilityAuditConfig_.showUnsupportedRulesWarning = false;
158 this.accessibilityAuditConfig_.auditRulesToIgnore = [
159 // The "elements with meaningful background image" accessibility
160 // audit (AX_IMAGE_01) does not apply, since Chrome doesn't
161 // disable background images in high-contrast mode like some
162 // browsers do.
163 "elementsWithMeaningfulBackgroundImage",
165 // Most WebUI pages are inside an IFrame, so the "web page should
166 // have a title that describes topic or purpose" test (AX_TITLE_01)
167 // generally does not apply.
168 "pageWithoutTitle",
170 // TODO(aboxhall): re-enable when crbug.com/267035 is fixed.
171 // Until then it's just noise.
172 "lowContrastElements",
175 return this.accessibilityAuditConfig_;
179 * Whether to treat accessibility issues (errors or warnings) as test
180 * failures. If true, any accessibility issues will cause the test to fail.
181 * If false, accessibility issues will cause a console.warn.
182 * Off by default to begin with; as we add the ability to suppress false
183 * positives, we will transition this to true.
184 * @type {boolean}
186 accessibilityIssuesAreErrors: false,
189 * Holds any accessibility results found during the accessibility audit.
190 * @type {Array.<Object>}
192 a11yResults_: [],
195 * Gets the list of accessibility errors found during the accessibility
196 * audit. Only for use in testing.
197 * @return {Array.<Object>}
199 getAccessibilityResults: function() {
200 return this.a11yResults_;
204 * Run accessibility checks after this test completes.
206 enableAccessibilityChecks: function() {
207 this.runAccessibilityChecks = true;
211 * Don't run accessibility checks after this test completes.
213 disableAccessibilityChecks: function() {
214 this.runAccessibilityChecks = false;
218 * Create a new class to handle |messageNames|, assign it to
219 * |this.mockHandler|, register its messages and return it.
220 * @return {Mock} Mock handler class assigned to |this.mockHandler|.
222 makeAndRegisterMockHandler: function(messageNames) {
223 var MockClass = makeMockClass(messageNames);
224 this.mockHandler = mock(MockClass);
225 registerMockMessageCallbacks(this.mockHandler, MockClass);
226 return this.mockHandler;
230 * Create a new class to handle |functionNames|, assign it to
231 * |this.mockGlobals|, register its global overrides, and return it.
232 * @return {Mock} Mock handler class assigned to |this.mockGlobals|.
233 * @see registerMockGlobals
235 makeAndRegisterMockGlobals: function(functionNames) {
236 var MockClass = makeMockClass(functionNames);
237 this.mockGlobals = mock(MockClass);
238 registerMockGlobals(this.mockGlobals, MockClass);
239 return this.mockGlobals;
243 * Create a container of mocked standalone functions to handle
244 * '.'-separated |apiNames|, assign it to |this.mockApis|, register its API
245 * overrides and return it.
246 * @return {Mock} Mock handler class.
247 * @see makeMockFunctions
248 * @see registerMockApis
250 makeAndRegisterMockApis: function (apiNames) {
251 var apiMockNames = apiNames.map(function(name) {
252 return name.replace(/\./g, '_');
255 this.mockApis = makeMockFunctions(apiMockNames);
256 registerMockApis(this.mockApis);
257 return this.mockApis;
261 * Create a container of mocked standalone functions to handle
262 * |functionNames|, assign it to |this.mockLocalFunctions| and return it.
263 * @param {!Array.<string>} functionNames
264 * @return {Mock} Mock handler class.
265 * @see makeMockFunctions
267 makeMockLocalFunctions: function(functionNames) {
268 this.mockLocalFunctions = makeMockFunctions(functionNames);
269 return this.mockLocalFunctions;
273 * Override this method to perform initialization during preload (such as
274 * creating mocks and registering handlers).
275 * @type {Function}
277 preLoad: function() {},
280 * Override this method to perform tasks before running your test.
281 * @type {Function}
283 setUp: function() {},
286 * Override this method to perform tasks after running your test. If you
287 * create a mock class, you must call Mock4JS.verifyAllMocks() in this
288 * phase.
289 * @type {Function}
291 tearDown: function() {
292 Mock4JS.verifyAllMocks();
296 * Called to run the body from the perspective of this fixture.
297 * @type {Function}
299 runTest: function(testBody) {
300 testBody.call(this);
304 * Called to run the accessibility audit from the perspective of this
305 * fixture.
307 runAccessibilityAudit: function() {
308 if (!this.runAccessibilityChecks || typeof document === 'undefined')
309 return;
311 var auditConfig = this.accessibilityAuditConfig;
312 if (!runAccessibilityAudit(this.a11yResults_, auditConfig)) {
313 var report = accessibilityAuditReport(this.a11yResults_);
314 if (this.accessibilityIssuesAreErrors)
315 throw new Error(report);
316 else
317 console.warn(report);
322 * Create a closure function for continuing the test at a later time. May be
323 * used as a listener function.
324 * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate
325 * time.
326 * @param {Function} completion The function to call to complete the test.
327 * @param {...*} var_args Arguments to pass when calling completionAction.
328 * @return {function(): void} Return a function, bound to this test fixture,
329 * which continues the test.
331 continueTest: function(whenTestDone, completion) {
332 var savedArgs = new SaveMockArguments();
333 var completionAction = new CallFunctionAction(
334 this, savedArgs, completion,
335 Array.prototype.slice.call(arguments, 2));
336 if (whenTestDone === WhenTestDone.DEFAULT)
337 whenTestDone = WhenTestDone.ASSERT;
338 var runAll = new RunAllAction(
339 true, whenTestDone, [completionAction]);
340 return function() {
341 savedArgs.arguments = Array.prototype.slice.call(arguments);
342 runAll.invoke();
347 * Call this during setUp to defer the call to runTest() until later. The
348 * caller must call the returned function at some point to run the test.
349 * @type {Function}
350 * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate
351 * time.
352 * @param {...*} var_args Arguments to pass when running the
353 * |currentTestCase|.
354 * @return {function(): void} A function which will run the current body of
355 * the currentTestCase.
357 deferRunTest: function(whenTestDone) {
358 if (whenTestDone === WhenTestDone.DEFAULT)
359 whenTestDone = WhenTestDone.ALWAYS;
361 return currentTestCase.deferRunTest.apply(
362 currentTestCase, [whenTestDone].concat(
363 Array.prototype.slice.call(arguments, 1)));
368 * This class is not exported and is available to hold the state of the
369 * |currentTestCase| throughout preload and test run.
370 * @param {string} name The name of the test case.
371 * @param {Test} fixture The fixture object for this test case.
372 * @param {Function} body The code to run for the test.
373 * @constructor
375 function TestCase(name, fixture, body) {
376 this.name = name;
377 this.fixture = fixture;
378 this.body = body;
381 TestCase.prototype = {
383 * The name of this test.
384 * @type {string}
386 name: null,
389 * The test fixture to set |this| to when running the test |body|.
390 * @type {testing.Test}
392 fixture: null,
395 * The test body to execute in runTest().
396 * @type {Function}
398 body: null,
401 * True when the test fixture will run the test later.
402 * @type {boolean}
403 * @private
405 deferred_: false,
408 * Called at preload time, proxies to the fixture.
409 * @type {Function}
411 preLoad: function(name) {
412 if (this.fixture)
413 this.fixture.preLoad();
417 * Called before a test runs.
419 setUp: function() {
420 if (this.fixture)
421 this.fixture.setUp();
425 * Called before a test is torn down (by testDone()).
427 tearDown: function() {
428 if (this.fixture)
429 this.fixture.tearDown();
433 * Called to run this test's body.
435 runTest: function() {
436 if (this.body && this.fixture)
437 this.fixture.runTest(this.body);
441 * Called after a test is run (in testDone) to test accessibility.
443 runAccessibilityAudit: function() {
444 if (this.fixture)
445 this.fixture.runAccessibilityAudit();
449 * Runs this test case with |this| set to the |fixture|.
451 * Note: Tests created with TEST_F may depend upon |this| being set to an
452 * instance of this.fixture. The current implementation of TEST creates a
453 * dummy constructor, but tests created with TEST should not rely on |this|
454 * being set.
455 * @type {Function}
457 run: function() {
458 try {
459 this.setUp();
460 } catch(e) {
461 // Mock4JSException doesn't inherit from Error, so fall back on
462 // toString().
463 console.error(e.stack || e.toString());
466 if (!this.deferred_)
467 this.runTest();
469 // tearDown called by testDone().
473 * Cause this TestCase to be deferred (don't call runTest()) until the
474 * returned function is called.
475 * @type {Function}
476 * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate
477 * time.
478 * @param {...*} var_args Arguments to pass when running the
479 * |currentTestCase|.
480 * @return {function(): void} A function thatwill run this TestCase when
481 * called.
483 deferRunTest: function(whenTestDone) {
484 this.deferred_ = true;
485 var savedArgs = new SaveMockArguments();
486 var completionAction = new CallFunctionAction(
487 this, savedArgs, this.runTest,
488 Array.prototype.slice.call(arguments, 1));
489 var runAll = new RunAllAction(
490 true, whenTestDone, [completionAction]);
491 return function() {
492 savedArgs.arguments = Array.prototype.slice.call(arguments);
493 runAll.invoke();
500 * Registry of javascript-defined callbacks for {@code chrome.send}.
501 * @type {Object}
503 var sendCallbacks = {};
506 * Registers the message, object and callback for {@code chrome.send}
507 * @param {string} name The name of the message to route to this |callback|.
508 * @param {Object} messageHandler Pass as |this| when calling the |callback|.
509 * @param {function(...)} callback Called by {@code chrome.send}.
510 * @see sendCallbacks
512 function registerMessageCallback(name, messageHandler, callback) {
513 sendCallbacks[name] = [messageHandler, callback];
517 * Register all methods of {@code mockClass.prototype} with messages of the
518 * same name as the method, using the proxy of the |mockObject| as the
519 * |messageHandler| when registering.
520 * @param {Mock4JS.Mock} mockObject The mock to register callbacks against.
521 * @param {function(new:Object)} mockClAss Constructor for the mocked class.
522 * @see registerMessageCallback
523 * @see overrideChrome
525 function registerMockMessageCallbacks(mockObject, mockClass) {
526 if (!deferGlobalOverrides && !originalChrome)
527 overrideChrome();
528 var mockProxy = mockObject.proxy();
529 for (var func in mockClass.prototype) {
530 if (typeof mockClass.prototype[func] === 'function') {
531 registerMessageCallback(func, mockProxy, mockProxy[func]);
537 * Holds the mapping of name -> global override information.
538 * @type {Object}
540 var globalOverrides = {};
543 * When preloading JavaScript libraries, this is true until the
544 * DOMContentLoaded event has been received as globals cannot be overridden
545 * until the page has loaded its JavaScript.
546 * @type {boolean}
548 var deferGlobalOverrides = false;
551 * Override the global function |funcName| with its registered mock. This
552 * should not be called twice for the same |funcName|.
553 * @param {string} funcName The name of the global function to override.
555 function overrideGlobal(funcName) {
556 assertNotEquals(undefined, this[funcName]);
557 var globalOverride = globalOverrides[funcName];
558 assertNotEquals(undefined, globalOverride);
559 assertEquals(undefined, globalOverride.original);
560 globalOverride.original = this[funcName];
561 this[funcName] = globalOverride.callback.bind(globalOverride.object);
565 * Registers the global function name, object and callback.
566 * @param {string} name The name of the message to route to this |callback|.
567 * @param {Object} object Pass as |this| when calling the |callback|.
568 * @param {function(...)} callback Called by {@code chrome.send}.
569 * @see overrideGlobal
571 function registerMockGlobal(name, object, callback) {
572 assertEquals(undefined, globalOverrides[name]);
573 globalOverrides[name] = {
574 object: object,
575 callback: callback,
578 if (!deferGlobalOverrides)
579 overrideGlobal(name);
583 * Registers the mock API call and its function.
584 * @param {string} name The '_'-separated name of the API call.
585 * @param {function(...)} theFunction Mock function for this API call.
587 function registerMockApi(name, theFunction) {
588 var path = name.split('_');
590 var namespace = this;
591 for(var i = 0; i < path.length - 1; i++) {
592 var fieldName = path[i];
593 if(!namespace[fieldName])
594 namespace[fieldName] = {};
596 namespace = namespace[fieldName];
599 var fieldName = path[path.length-1];
600 namespace[fieldName] = theFunction;
604 * Empty function for use in making mocks.
605 * @const
607 function emptyFunction() {}
610 * Make a mock from the supplied |methodNames| array.
611 * @param {Array.<string>} methodNames Array of names of methods to mock.
612 * @return {Function} Constructor with prototype filled in with methods
613 * matching |methodNames|.
615 function makeMockClass(methodNames) {
616 function MockConstructor() {}
617 for(var i = 0; i < methodNames.length; i++)
618 MockConstructor.prototype[methodNames[i]] = emptyFunction;
619 return MockConstructor;
623 * Create a new class to handle |functionNames|, add method 'functions()'
624 * that returns a container of standalone functions based on the mock class
625 * members, and return it.
626 * @return {Mock} Mock handler class.
628 function makeMockFunctions(functionNames) {
629 var MockClass = makeMockClass(functionNames);
630 var mockFunctions = mock(MockClass);
631 var mockProxy = mockFunctions.proxy();
633 mockFunctions.functions_ = {};
635 for (var func in MockClass.prototype) {
636 if (typeof MockClass.prototype[func] === 'function')
637 mockFunctions.functions_[func] = mockProxy[func].bind(mockProxy);
640 mockFunctions.functions = function () {
641 return this.functions_;
644 return mockFunctions;
648 * Register all methods of {@code mockClass.prototype} as overrides to global
649 * functions of the same name as the method, using the proxy of the
650 * |mockObject| to handle the functions.
651 * @param {Mock4JS.Mock} mockObject The mock to register callbacks against.
652 * @param {function(new:Object)} mockClass Constructor for the mocked class.
653 * @see registerMockGlobal
655 function registerMockGlobals(mockObject, mockClass) {
656 var mockProxy = mockObject.proxy();
657 for (var func in mockClass.prototype) {
658 if (typeof mockClass.prototype[func] === 'function')
659 registerMockGlobal(func, mockProxy, mockProxy[func]);
664 * Register all functions in |mockObject.functions()| as global API calls.
665 * @param {Mock4JS.Mock} mockObject The mock to register callbacks against.
666 * @see registerMockApi
668 function registerMockApis(mockObject) {
669 var functions = mockObject.functions();
670 for (var func in functions) {
671 if (typeof functions[func] === 'function')
672 registerMockApi(func, functions[func]);
677 * Overrides {@code chrome.send} for routing messages to javascript
678 * functions. Also falls back to sending with the original chrome object.
679 * @param {string} messageName The message to route.
681 function send(messageName) {
682 var callback = sendCallbacks[messageName];
683 if (callback != undefined)
684 callback[1].apply(callback[0], Array.prototype.slice.call(arguments, 1));
685 else
686 this.__proto__.send.apply(this.__proto__, arguments);
690 * Provides a mechanism for assert* and expect* methods to fetch the signature
691 * of their caller. Assert* methods should |registerCall| and expect* methods
692 * should set |isExpect| and |expectName| properties to indicate that the
693 * interesting caller is one more level up the stack.
695 function CallHelper() {
696 this.__proto__ = CallHelper.prototype;
699 CallHelper.prototype = {
701 * Holds the mapping of (callerCallerString, callerName) -> count of times
702 * called.
703 * @type {Object.<string, Object.<string, number>>}
705 counts_: {},
708 * This information about the caller is needed from most of the following
709 * routines.
710 * @param {Function} caller the caller of the assert* routine.
711 * @return {{callerName: string, callercallerString: string}} stackInfo
712 * @private
714 getCallerInfo_: function(caller) {
715 var callerName = caller.name;
716 var callerCaller = caller.caller;
717 if (callerCaller['isExpect']) {
718 callerName = callerCaller.expectName;
719 callerCaller = callerCaller.caller;
721 var callerCallerString = callerCaller.toString();
722 return {
723 callerName: callerName,
724 callerCallerString: callerCallerString,
729 * Register a call to an assertion class.
731 registerCall: function() {
732 var stackInfo = this.getCallerInfo_(arguments.callee.caller);
733 if (!(stackInfo.callerCallerString in this.counts_))
734 this.counts_[stackInfo.callerCallerString] = {};
735 if (!(stackInfo.callerName in this.counts_[stackInfo.callerCallerString]))
736 this.counts_[stackInfo.callerCallerString][stackInfo.callerName] = 0;
737 ++this.counts_[stackInfo.callerCallerString][stackInfo.callerName];
741 * Get the call signature of this instance of the caller's call to this
742 * function.
743 * @param {Function} caller The caller of the assert* routine.
744 * @return {String} Call signature.
745 * @private
747 getCall_: function(caller) {
748 var stackInfo = this.getCallerInfo_(caller);
749 var count =
750 this.counts_[stackInfo.callerCallerString][stackInfo.callerName];
752 // Allow pattern to match multiple lines for text wrapping.
753 var callerRegExp =
754 new RegExp(stackInfo.callerName + '\\((.|\\n|\\r)*?\\);', 'g');
756 // Find all matches allowing wrap around such as when a helper function
757 // calls assert/expect calls and that helper function is called multiple
758 // times.
759 var matches = stackInfo.callerCallerString.match(callerRegExp);
760 var match = matches[(count - 1) % matches.length];
762 // Chop off the trailing ';'.
763 return match.substring(0, match.length-1);
767 * Returns the text of the call signature and any |message|.
768 * @param {string=} message Addtional message text from caller.
770 getCallMessage: function(message) {
771 var callMessage = this.getCall_(arguments.callee.caller);
772 if (message)
773 callMessage += ': ' + message;
774 return callMessage;
779 * Help register calls for better error reporting.
780 * @type {CallHelper}
782 var helper = new CallHelper();
785 * true when testDone has been called.
786 * @type {boolean}
788 var testIsDone = false;
791 * Holds the errors, if any, caught by expects so that the test case can
792 * fail. Cleared when results are reported from runTest() or testDone().
793 * @type {Array.<Error>}
795 var errors = [];
798 * URL to dummy WebUI page for testing framework.
799 * @type {string}
801 var DUMMY_URL = 'chrome://DummyURL';
804 * Resets test state by clearing |errors| and |testIsDone| flags.
806 function resetTestState() {
807 errors.splice(0, errors.length);
808 testIsDone = false;
812 * Notifies the running browser test of the test results. Clears |errors|.
813 * @param {Array.<boolean, string>=} result When passed, this is used for the
814 * testResult message.
816 function testDone(result) {
817 if (!testIsDone) {
818 testIsDone = true;
819 if (currentTestCase) {
820 var ok = true;
821 ok = createExpect(currentTestCase.runAccessibilityAudit.bind(
822 currentTestCase)).call(null) && ok;
823 ok = createExpect(currentTestCase.tearDown.bind(
824 currentTestCase)).call(null) && ok;
826 if (!ok && result)
827 result = [false, errorsToMessage(errors, result[1])];
829 currentTestCase = null;
831 if (!result)
832 result = testResult();
833 if (chrome.send) {
834 // For WebUI tests.
835 chrome.send('testResult', result);
836 } else if (window.domAutomationController.send) {
837 // For extension tests.
838 valueResult = { 'result': result[0], message: result[1] };
839 window.domAutomationController.send(JSON.stringify(valueResult));
841 errors.splice(0, errors.length);
842 } else {
843 console.warn('testIsDone already');
848 * Converts each Error in |errors| to a suitable message, adding them to
849 * |message|, and returns the message string.
850 * @param {Array.<Error>} errors Array of errors to add to |message|.
851 * @param {string?} message When supplied, error messages are appended to it.
852 * @return {string} |message| + messages of all |errors|.
854 function errorsToMessage(errors, message) {
855 for (var i = 0; i < errors.length; ++i) {
856 var errorMessage = errors[i].stack || errors[i].message;
857 if (message)
858 message += '\n';
860 message += 'Failed: ' + currentTestFunction + '(' +
861 currentTestArguments.map(JSON.stringify) +
862 ')\n' + errorMessage;
864 return message;
868 * Returns [success, message] & clears |errors|.
869 * @param {boolean} errorsOk When true, errors are ok.
870 * @return {Array.<boolean, string>}
872 function testResult(errorsOk) {
873 var result = [true, ''];
874 if (errors.length)
875 result = [!!errorsOk, errorsToMessage(errors)];
877 return result;
880 // Asserts.
881 // Use the following assertions to verify a condition within a test.
882 // If assertion fails, throw an Error with information pertinent to the test.
885 * When |test| !== true, aborts the current test.
886 * @param {boolean} test The predicate to check against |expected|.
887 * @param {string=} message The message to include in the Error thrown.
888 * @throws {Error} upon failure.
890 function assertTrue(test, message) {
891 helper.registerCall();
892 if (test !== true)
893 throw new Error(
894 'Test Error ' + helper.getCallMessage(message) + ': ' + test);
898 * When |test| !== false, aborts the current test.
899 * @param {boolean} test The predicate to check against |expected|.
900 * @param {string=} message The message to include in the Error thrown.
901 * @throws {Error} upon failure.
903 function assertFalse(test, message) {
904 helper.registerCall();
905 if (test !== false)
906 throw new Error(
907 'Test Error ' + helper.getCallMessage(message) + ': ' + test);
911 * When |val1| < |val2|, aborts the current test.
912 * @param {number} val1 The number expected to be >= |val2|.
913 * @param {number} val2 The number expected to be < |val1|.
914 * @param {string=} message The message to include in the Error thrown.
916 function assertGE(val1, val2, message) {
917 helper.registerCall();
918 if (val1 < val2) {
919 throw new Error(
920 'Test Error ' + helper.getCallMessage(message) + val1 + '<' + val2);
925 * When |val1| <= |val2|, aborts the current test.
926 * @param {number} val1 The number expected to be > |val2|.
927 * @param {number} val2 The number expected to be <= |val1|.
928 * @param {string=} message The message to include in the Error thrown.
930 function assertGT(val1, val2, message) {
931 helper.registerCall();
932 if (val1 <= val2) {
933 throw new Error(
934 'Test Error ' + helper.getCallMessage(message) + val1 + '<=' + val2);
939 * When |expected| !== |actual|, aborts the current test.
940 * @param {*} expected The expected value of |actual|.
941 * @param {*} actual The predicate to check against |expected|.
942 * @param {string=} message The message to include in the Error thrown.
943 * @throws {Error} upon failure.
945 function assertEquals(expected, actual, message) {
946 helper.registerCall();
947 if (expected != actual) {
948 throw new Error(
949 'Test Error ' + helper.getCallMessage(message) +
950 '\nActual: ' + actual + '\nExpected: ' + expected);
952 if (typeof expected !== typeof actual) {
953 throw new Error(
954 'Test Error (type mismatch) ' + helper.getCallMessage(message) +
955 '\nActual Type: ' + typeof actual +
956 '\nExpected Type:' + typeof expected);
961 * When |val1| > |val2|, aborts the current test.
962 * @param {number} val1 The number expected to be <= |val2|.
963 * @param {number} val2 The number expected to be > |val1|.
964 * @param {string=} message The message to include in the Error thrown.
966 function assertLE(val1, val2, message) {
967 helper.registerCall();
968 if (val1 > val2) {
969 throw new Error(
970 'Test Error ' + helper.getCallMessage(message) + val1 + '>' + val2);
975 * When |val1| >= |val2|, aborts the current test.
976 * @param {number} val1 The number expected to be < |val2|.
977 * @param {number} val2 The number expected to be >= |val1|.
978 * @param {string=} message The message to include in the Error thrown.
980 function assertLT(val1, val2, message) {
981 helper.registerCall();
982 if (val1 >= val2) {
983 throw new Error(
984 'Test Error ' + helper.getCallMessage(message) + val1 + '>=' + val2);
989 * When |notExpected| === |actual|, aborts the current test.
990 * @param {*} notExpected The expected value of |actual|.
991 * @param {*} actual The predicate to check against |notExpected|.
992 * @param {string=} message The message to include in the Error thrown.
993 * @throws {Error} upon failure.
995 function assertNotEquals(notExpected, actual, message) {
996 helper.registerCall();
997 if (notExpected === actual) {
998 throw new Error(
999 'Test Error ' + helper.getCallMessage(message) +
1000 '\nActual: ' + actual + '\nnotExpected: ' + notExpected);
1005 * Always aborts the current test.
1006 * @param {string=} message The message to include in the Error thrown.
1007 * @throws {Error} always.
1009 function assertNotReached(message) {
1010 helper.registerCall();
1011 throw new Error(helper.getCallMessage(message));
1015 * Run an accessibility audit on the current page state.
1016 * @type {Function}
1017 * @param {Array} a11yResults
1018 * @param {axs.AuditConfigutarion=} opt_config
1019 * @return {boolean} Whether there were any errors or warnings
1020 * @private
1022 function runAccessibilityAudit(a11yResults, opt_config) {
1023 var auditResults = axs.Audit.run(opt_config);
1024 for (var i = 0; i < auditResults.length; i++) {
1025 var auditResult = auditResults[i];
1026 if (auditResult.result == axs.constants.AuditResult.FAIL) {
1027 var auditRule = auditResult.rule;
1028 // TODO(aboxhall): more useful error messages (sadly non-trivial)
1029 a11yResults.push(auditResult);
1032 // TODO(aboxhall): have strict (no errors or warnings) vs non-strict
1033 // (warnings ok)
1034 // TODO(aboxhall): some kind of info logging for warnings only??
1035 return (a11yResults.length == 0);
1039 * Concatenates the accessibility error messages for each result in
1040 * |a11yResults| and
1041 * |a11yWarnings| in to an accessibility report, appends it to the given
1042 * |message| and returns the resulting message string.
1043 * @param {Array.<string>} a11yResults The list of accessibility results
1044 * @return {string} |message| + accessibility report.
1046 function accessibilityAuditReport(a11yResults, message) {
1047 message = message ? message + '\n\n' : '\n';
1048 message += 'Accessibility issues found on ' + window.location.href + '\n';
1049 message += axs.Audit.createReport(a11yResults);
1050 return message;
1054 * Asserts that the current page state passes the accessibility audit.
1055 * @param {Array=} opt_results Array to fill with results, if desired.
1057 function assertAccessibilityOk(opt_results) {
1058 helper.registerCall();
1059 var a11yResults = opt_results || [];
1060 var auditConfig = currentTestCase.fixture.accessibilityAuditConfig;
1061 if (!runAccessibilityAudit(a11yResults, auditConfig))
1062 throw new Error(accessibilityAuditReport(a11yResults));
1066 * Creates a function based upon a function that thows an exception on
1067 * failure. The new function stuffs any errors into the |errors| array for
1068 * checking by runTest. This allows tests to continue running other checks,
1069 * while failing the overall test if any errors occurrred.
1070 * @param {Function} assertFunc The function which may throw an Error.
1071 * @return {function(...*):bool} A function that applies its arguments to
1072 * |assertFunc| and returns true if |assertFunc| passes.
1073 * @see errors
1074 * @see runTestFunction
1076 function createExpect(assertFunc) {
1077 var expectFunc = function() {
1078 try {
1079 assertFunc.apply(null, arguments);
1080 } catch (e) {
1081 errors.push(e);
1082 return false;
1084 return true;
1086 expectFunc.isExpect = true;
1087 expectFunc.expectName = assertFunc.name.replace(/^assert/, 'expect');
1088 return expectFunc;
1092 * This is the starting point for tests run by WebUIBrowserTest. If an error
1093 * occurs, it reports a failure and a message created by joining individual
1094 * error messages. This supports sync tests and async tests by calling
1095 * testDone() when |isAsync| is not true, relying on async tests to call
1096 * testDone() when they complete.
1097 * @param {boolean} isAsync When false, call testDone() with the test result
1098 * otherwise only when assertions are caught.
1099 * @param {string} testFunction The function name to call.
1100 * @param {Array} testArguments The arguments to call |testFunction| with.
1101 * @return {boolean} true always to signal successful execution (but not
1102 * necessarily successful results) of this test.
1103 * @see errors
1104 * @see runTestFunction
1106 function runTest(isAsync, testFunction, testArguments) {
1107 // Avoid eval() if at all possible, since it will not work on pages
1108 // that have enabled content-security-policy.
1109 var testBody = this[testFunction]; // global object -- not a method.
1110 var testName = testFunction;
1112 // Depending on how we were called, |this| might not resolve to the global
1113 // context.
1114 if (testName == 'RUN_TEST_F' && testBody === undefined)
1115 testBody = RUN_TEST_F;
1117 if (typeof testBody === "undefined") {
1118 testBody = eval(testFunction);
1119 testName = testBody.toString();
1121 if (testBody != RUN_TEST_F) {
1122 console.log('Running test ' + testName);
1125 // Async allow expect errors, but not assert errors.
1126 var result = runTestFunction(testFunction, testBody, testArguments,
1127 isAsync);
1128 if (!isAsync || !result[0])
1129 testDone(result);
1130 return true;
1134 * This is the guts of WebUIBrowserTest. It runs the test surrounded by an
1135 * expect to catch Errors. If |errors| is non-empty, it reports a failure and
1136 * a message by joining |errors|. Consumers can use this to use assert/expect
1137 * functions asynchronously, but are then responsible for reporting errors to
1138 * the browser themselves through testDone().
1139 * @param {string} testFunction The function name to report on failure.
1140 * @param {Function} testBody The function to call.
1141 * @param {Array} testArguments The arguments to call |testBody| with.
1142 * @param {boolean} onlyAssertFails When true, only assertions cause failing
1143 * testResult.
1144 * @return {Array.<boolean, string>} [test-succeeded, message-if-failed]
1145 * @see createExpect
1146 * @see testResult
1148 function runTestFunction(testFunction, testBody, testArguments,
1149 onlyAssertFails) {
1150 currentTestFunction = testFunction;
1151 currentTestArguments = testArguments;
1152 var ok = createExpect(testBody).apply(null, testArguments);
1153 return testResult(onlyAssertFails && ok);
1157 * Creates a new test case for the given |testFixture| and |testName|. Assumes
1158 * |testFixture| describes a globally available subclass of type Test.
1159 * @param {string} testFixture The fixture for this test case.
1160 * @param {string} testName The name for this test case.
1161 * @return {TestCase} A newly created TestCase.
1163 function createTestCase(testFixture, testName) {
1164 var fixtureConstructor = this[testFixture];
1165 var testBody = fixtureConstructor.testCaseBodies[testName];
1166 var fixture = new fixtureConstructor();
1167 fixture.name = testFixture;
1168 return new TestCase(testName, fixture, testBody);
1172 * Overrides the |chrome| object to enable mocking calls to chrome.send().
1174 function overrideChrome() {
1175 if (originalChrome) {
1176 console.error('chrome object already overridden');
1177 return;
1180 originalChrome = chrome;
1181 chrome = {
1182 __proto__: originalChrome,
1183 send: send,
1184 originalSend: originalChrome.send.bind(originalChrome),
1189 * Used by WebUIBrowserTest to preload the javascript libraries at the
1190 * appropriate time for javascript injection into the current page. This
1191 * creates a test case and calls its preLoad for any early initialization such
1192 * as registering handlers before the page's javascript runs it's OnLoad
1193 * method. This is called before the page is loaded, so the |chrome| object is
1194 * not yet bound and this DOMContentLoaded listener will be called first to
1195 * override |chrome| in order to route messages registered in |sendCallbacks|.
1196 * @param {string} testFixture The test fixture name.
1197 * @param {string} testName The test name.
1198 * @see sendCallbacks
1200 function preloadJavascriptLibraries(testFixture, testName) {
1201 deferGlobalOverrides = true;
1203 // The document seems to change from the point of preloading to the point of
1204 // events (and doesn't fire), whereas the window does not. Listening to the
1205 // capture phase allows this event to fire first.
1206 window.addEventListener('DOMContentLoaded', function() {
1207 overrideChrome();
1209 // Override globals at load time so they will be defined.
1210 assertTrue(deferGlobalOverrides);
1211 deferGlobalOverrides = false;
1212 for (var funcName in globalOverrides)
1213 overrideGlobal(funcName);
1214 }, true);
1215 currentTestCase = createTestCase(testFixture, testName);
1216 currentTestCase.preLoad();
1220 * During generation phase, this outputs; do nothing at runtime.
1222 function GEN() {}
1225 * During generation phase, this outputs; do nothing at runtime.
1227 function GEN_INCLUDE() {}
1230 * At runtime, register the testName with a test fixture. Since this method
1231 * doesn't have a test fixture, create a dummy fixture to hold its |name|
1232 * and |testCaseBodies|.
1233 * @param {string} testCaseName The name of the test case.
1234 * @param {string} testName The name of the test function.
1235 * @param {Function} testBody The body to execute when running this test.
1237 function TEST(testCaseName, testName, testBody) {
1238 var fixtureConstructor = this[testCaseName];
1239 if (fixtureConstructor === undefined) {
1240 fixtureConstructor = function() {};
1241 this[testCaseName] = fixtureConstructor;
1242 fixtureConstructor.prototype = {
1243 __proto__: Test.prototype,
1244 name: testCaseName,
1246 fixtureConstructor.testCaseBodies = {};
1248 fixtureConstructor.testCaseBodies[testName] = testBody;
1252 * At runtime, register the testName with its fixture. Stuff the |name| into
1253 * the |testFixture|'s prototype, if needed, and the |testCaseBodies| into its
1254 * constructor.
1255 * @param {string} testFixture The name of the test fixture class.
1256 * @param {string} testName The name of the test function.
1257 * @param {Function} testBody The body to execute when running this test.
1259 function TEST_F(testFixture, testName, testBody) {
1260 var fixtureConstructor = this[testFixture];
1261 if (!fixtureConstructor.prototype.name)
1262 fixtureConstructor.prototype.name = testFixture;
1263 if (fixtureConstructor['testCaseBodies'] === undefined)
1264 fixtureConstructor.testCaseBodies = {};
1265 fixtureConstructor.testCaseBodies[testName] = testBody;
1269 * RunJavascriptTestF uses this as the |testFunction| when invoking
1270 * runTest. If |currentTestCase| is non-null at this point, verify that
1271 * |testFixture| and |testName| agree with the preloaded values. Create
1272 * |currentTestCase|, if needed, run it, and clear the |currentTestCase|.
1273 * @param {string} testFixture The name of the test fixture class.
1274 * @param {string} testName The name of the test function.
1275 * @see preloadJavascriptLibraries
1276 * @see runTest
1278 function RUN_TEST_F(testFixture, testName) {
1279 if (!currentTestCase)
1280 currentTestCase = createTestCase(testFixture, testName);
1281 assertEquals(currentTestCase.name, testName);
1282 assertEquals(currentTestCase.fixture.name, testFixture);
1283 console.log('Running TestCase ' + testFixture + '.' + testName);
1284 currentTestCase.run();
1288 * This Mock4JS matcher object pushes each |actualArgument| parameter to
1289 * match() calls onto |args|.
1290 * @param {Array} args The array to push |actualArgument| onto.
1291 * @param {Object} realMatcher The real matcher check arguments with.
1292 * @constructor
1293 * @extends {realMatcher}
1295 function SaveMockArgumentMatcher(args, realMatcher) {
1296 this.arguments_ = args;
1297 this.realMatcher_ = realMatcher;
1300 SaveMockArgumentMatcher.prototype = {
1302 * Holds the arguments to push each |actualArgument| onto.
1303 * @type {Array}
1304 * @private
1306 arguments_: null,
1309 * The real Mock4JS matcher object to check arguments with.
1310 * @type {Object}
1312 realMatcher_: null,
1315 * Pushes |actualArgument| onto |arguments_| and call |realMatcher_|. Clears
1316 * |arguments_| on non-match.
1317 * @param {*} actualArgument The argument to match and save.
1318 * @return {boolean} Result of calling the |realMatcher|.
1320 argumentMatches: function(actualArgument) {
1321 this.arguments_.push(actualArgument);
1322 var match = this.realMatcher_.argumentMatches(actualArgument);
1323 if (!match)
1324 this.arguments_.splice(0, this.arguments_.length);
1326 return match;
1330 * Proxy to |realMatcher_| for description.
1331 * @return {string} Description of this Mock4JS matcher.
1333 describe: function() {
1334 return this.realMatcher_.describe();
1339 * Actions invoked by Mock4JS's "will()" syntax do not receive arguments from
1340 * the mocked method. This class works with SaveMockArgumentMatcher to save
1341 * arguments so that the invoked Action can pass arguments through to the
1342 * invoked function.
1343 * @param {!Object} realMatcher The real matcher to perform matching with.
1344 * @constructor
1346 function SaveMockArguments() {
1347 this.arguments = [];
1350 SaveMockArguments.prototype = {
1352 * Wraps the |realMatcher| with an object which will push its argument onto
1353 * |arguments| and call realMatcher.
1354 * @param {Object} realMatcher A Mock4JS matcher object for this argument.
1355 * @return {SaveMockArgumentMatcher} A new matcher which will push its
1356 * argument onto |arguments|.
1358 match: function(realMatcher) {
1359 return new SaveMockArgumentMatcher(this.arguments, realMatcher);
1363 * Remember the argument passed to this stub invocation.
1364 * @type {Array}
1366 arguments: null,
1370 * CallFunctionAction is provided to allow mocks to have side effects.
1371 * @param {Object} obj The object to set |this| to when calling |func_|.
1372 * @param {?SaveMockArguments} savedArgs when non-null, saved arguments are
1373 * passed to |func|.
1374 * @param {Function} func The function to call.
1375 * @param {Array=} args Any arguments to pass to func.
1376 * @constructor
1378 function CallFunctionAction(obj, savedArgs, func, args) {
1379 this.obj_ = obj;
1380 this.savedArgs_ = savedArgs;
1381 this.func_ = func;
1382 this.args_ = args ? args : [];
1385 CallFunctionAction.prototype = {
1387 * Set |this| to |obj_| when calling |func_|.
1388 * @type {?Object}
1390 obj_: null,
1393 * The SaveMockArguments to hold arguments when invoking |func_|.
1394 * @type {?SaveMockArguments}
1395 * @private
1397 savedArgs_: null,
1400 * The function to call when invoked.
1401 * @type {!Function}
1402 * @private
1404 func_: null,
1407 * Arguments to pass to |func_| when invoked.
1408 * @type {!Array}
1410 args_: null,
1413 * Accessor for |func_|.
1414 * @return {Function} The function to invoke.
1416 get func() {
1417 return this.func_;
1421 * Called by Mock4JS when using .will() to specify actions for stubs() or
1422 * expects(). Clears |savedArgs_| so it can be reused.
1423 * @return The results of calling |func_| with the concatenation of
1424 * |savedArgs_| and |args_|.
1426 invoke: function() {
1427 var prependArgs = [];
1428 if (this.savedArgs_) {
1429 prependArgs = this.savedArgs_.arguments.splice(
1430 0, this.savedArgs_.arguments.length);
1432 return this.func.apply(this.obj_, prependArgs.concat(this.args_));
1436 * Describe this action to Mock4JS.
1437 * @return {string} A description of this action.
1439 describe: function() {
1440 return 'calls the given function with saved arguments and ' + this.args_;
1445 * Syntactic sugar for use with will() on a Mock4JS.Mock.
1446 * @param {Function} func The function to call when the method is invoked.
1447 * @param {...*} var_args Arguments to pass when calling func.
1448 * @return {CallFunctionAction} Action for use in will.
1450 function callFunction(func) {
1451 return new CallFunctionAction(
1452 null, null, func, Array.prototype.slice.call(arguments, 1));
1456 * Syntactic sugar for use with will() on a Mock4JS.Mock.
1457 * @param {SaveMockArguments} savedArgs Arguments saved with this object
1458 * are passed to |func|.
1459 * @param {Function} func The function to call when the method is invoked.
1460 * @param {...*} var_args Arguments to pass when calling func.
1461 * @return {CallFunctionAction} Action for use in will.
1463 function callFunctionWithSavedArgs(savedArgs, func) {
1464 return new CallFunctionAction(
1465 null, savedArgs, func, Array.prototype.slice.call(arguments, 2));
1469 * CallGlobalAction as a subclass of CallFunctionAction looks up the original
1470 * global object in |globalOverrides| using |funcName| as the key. This allows
1471 * tests, which need to wait until a global function to be called in order to
1472 * start the test to run the original function. When used with runAllActions
1473 * or runAllActionsAsync, Mock4JS expectations may call start or continue the
1474 * test after calling the original function.
1475 * @param {?SaveMockArguments} savedArgs when non-null, saved arguments are
1476 * passed to the global function |funcName|.
1477 * @param {string} funcName The name of the global function to call.
1478 * @param {Array} args Any arguments to pass to func.
1479 * @constructor
1480 * @extends {CallFunctionAction}
1481 * @see globalOverrides
1483 function CallGlobalAction(savedArgs, funcName, args) {
1484 CallFunctionAction.call(this, null, savedArgs, funcName, args);
1487 CallGlobalAction.prototype = {
1488 __proto__: CallFunctionAction.prototype,
1491 * Fetch and return the original global function to call.
1492 * @return {Function} The global function to invoke.
1493 * @override
1495 get func() {
1496 var func = globalOverrides[this.func_].original;
1497 assertNotEquals(undefined, func);
1498 return func;
1503 * Syntactic sugar for use with will() on a Mock4JS.Mock.
1504 * @param {SaveMockArguments} savedArgs Arguments saved with this object
1505 * are passed to the global function |funcName|.
1506 * @param {string} funcName The name of a registered mock global function to
1507 * call when the method is invoked.
1508 * @param {...*} var_args Arguments to pass when calling func.
1509 * @return {CallGlobalAction} Action for use in Mock4JS will().
1511 function callGlobalWithSavedArgs(savedArgs, funcName) {
1512 return new CallGlobalAction(
1513 savedArgs, funcName, Array.prototype.slice.call(arguments, 2));
1517 * When to call testDone().
1518 * @enum {number}
1520 var WhenTestDone = {
1522 * Default for the method called.
1524 DEFAULT: -1,
1527 * Never call testDone().
1529 NEVER: 0,
1532 * Call testDone() on assert failure.
1534 ASSERT: 1,
1537 * Call testDone() if there are any assert or expect failures.
1539 EXPECT: 2,
1542 * Always call testDone().
1544 ALWAYS: 3,
1548 * Runs all |actions|.
1549 * @param {boolean} isAsync When true, call testDone() on Errors.
1550 * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate
1551 * time.
1552 * @param {Array.<Object>} actions Actions to run.
1553 * @constructor
1555 function RunAllAction(isAsync, whenTestDone, actions) {
1556 this.isAsync_ = isAsync;
1557 this.whenTestDone_ = whenTestDone;
1558 this.actions_ = actions;
1561 RunAllAction.prototype = {
1563 * When true, call testDone() on Errors.
1564 * @type {boolean}
1565 * @private
1567 isAsync_: false,
1570 * Call testDone() at appropriate time.
1571 * @type {WhenTestDone}
1572 * @private
1573 * @see WhenTestDone
1575 whenTestDone_: WhenTestDone.ASSERT,
1578 * Holds the actions to execute when invoked.
1579 * @type {Array}
1580 * @private
1582 actions_: null,
1585 * Runs all |actions_|, returning the last one. When running in sync mode,
1586 * throws any exceptions to be caught by runTest() or
1587 * runTestFunction(). Call testDone() according to |whenTestDone_| setting.
1589 invoke: function() {
1590 try {
1591 var result;
1592 for(var i = 0; i < this.actions_.length; ++i)
1593 result = this.actions_[i].invoke();
1595 if ((this.whenTestDone_ == WhenTestDone.EXPECT && errors.length) ||
1596 this.whenTestDone_ == WhenTestDone.ALWAYS)
1597 testDone();
1599 return result;
1600 } catch (e) {
1601 if (!(e instanceof Error))
1602 e = new Error(e.toString());
1604 if (!this.isAsync_)
1605 throw e;
1607 errors.push(e);
1608 if (this.whenTestDone_ != WhenTestDone.NEVER)
1609 testDone();
1614 * Describe this action to Mock4JS.
1615 * @return {string} A description of this action.
1617 describe: function() {
1618 return 'Calls all actions: ' + this.actions_;
1623 * Syntactic sugar for use with will() on a Mock4JS.Mock.
1624 * @param {...Object} var_actions Actions to run.
1625 * @return {RunAllAction} Action for use in will.
1627 function runAllActions() {
1628 return new RunAllAction(false, WhenTestDone.NEVER,
1629 Array.prototype.slice.call(arguments));
1633 * Syntactic sugar for use with will() on a Mock4JS.Mock.
1634 * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate
1635 * time.
1636 * @param {...Object} var_actions Actions to run.
1637 * @return {RunAllAction} Action for use in will.
1639 function runAllActionsAsync(whenTestDone) {
1640 return new RunAllAction(true, whenTestDone,
1641 Array.prototype.slice.call(arguments, 1));
1645 * Syntactic sugar for use with will() on a Mock4JS.Mock.
1646 * Creates an action for will() that invokes a callback that the tested code
1647 * passes to a mocked function.
1648 * @param {SaveMockArguments} savedArgs Arguments that will contain the
1649 * callback once the mocked function is called.
1650 * @param {number} callbackParameter Index of the callback parameter in
1651 * |savedArgs|.
1652 * @param {...Object} var_args Arguments to pass to the callback.
1653 * @return {CallFunctionAction} Action for use in will().
1655 function invokeCallback(savedArgs, callbackParameter, var_args) {
1656 var callbackArguments = Array.prototype.slice.call(arguments, 2);
1657 return callFunction(function() {
1658 savedArgs.arguments[callbackParameter].apply(null, callbackArguments);
1660 // Mock4JS does not clear the saved args after invocation.
1661 // To allow reuse of the same SaveMockArguments for multiple
1662 // invocations with similar arguments, clear them here.
1663 savedArgs.arguments.splice(0, savedArgs.arguments.length);
1668 * Mock4JS matcher object that matches the actual argument and the expected
1669 * value iff their JSON represenations are same.
1670 * @param {Object} expectedValue
1671 * @constructor
1673 function MatchJSON(expectedValue) {
1674 this.expectedValue_ = expectedValue;
1677 MatchJSON.prototype = {
1679 * Checks that JSON represenation of the actual and expected arguments are
1680 * same.
1681 * @param {Object} actualArgument The argument to match.
1682 * @return {boolean} Result of the comparison.
1684 argumentMatches: function(actualArgument) {
1685 return JSON.stringify(this.expectedValue_) ===
1686 JSON.stringify(actualArgument);
1690 * Describes the matcher.
1691 * @return {string} Description of this Mock4JS matcher.
1693 describe: function() {
1694 return 'eqJSON(' + JSON.stringify(this.expectedValue_) + ')';
1699 * Builds a MatchJSON argument matcher for a given expected value.
1700 * @param {Object} expectedValue
1701 * @return {MatchJSON} Resulting Mock4JS matcher.
1703 function eqJSON(expectedValue) {
1704 return new MatchJSON(expectedValue);
1708 * Mock4JS matcher object that matches the actual argument and the expected
1709 * value iff the the string representation of the actual argument is equal to
1710 * the expected value.
1711 * @param {string} expectedValue
1712 * @constructor
1714 function MatchToString(expectedValue) {
1715 this.expectedValue_ = expectedValue;
1718 MatchToString.prototype = {
1720 * Checks that the the string representation of the actual argument matches
1721 * the expected value.
1722 * @param {*} actualArgument The argument to match.
1723 * @return {boolean} Result of the comparison.
1725 argumentMatches: function(actualArgument) {
1726 return this.expectedValue_ === String(actualArgument);
1730 * Describes the matcher.
1731 * @return {string} Description of this Mock4JS matcher.
1733 describe: function() {
1734 return 'eqToString("' + this.expectedValue_ + '")';
1739 * Builds a MatchToString argument matcher for a given expected value.
1740 * @param {Object} expectedValue
1741 * @return {MatchToString} Resulting Mock4JS matcher.
1743 function eqToString(expectedValue) {
1744 return new MatchToString(expectedValue);
1747 // Exports.
1748 testing.Test = Test;
1749 exports.testDone = testDone;
1750 exports.assertTrue = assertTrue;
1751 exports.assertFalse = assertFalse;
1752 exports.assertGE = assertGE;
1753 exports.assertGT = assertGT;
1754 exports.assertEquals = assertEquals;
1755 exports.assertLE = assertLE;
1756 exports.assertLT = assertLT;
1757 exports.assertNotEquals = assertNotEquals;
1758 exports.assertNotReached = assertNotReached;
1759 exports.assertAccessibilityOk = assertAccessibilityOk;
1760 exports.callFunction = callFunction;
1761 exports.callFunctionWithSavedArgs = callFunctionWithSavedArgs;
1762 exports.callGlobalWithSavedArgs = callGlobalWithSavedArgs;
1763 exports.eqJSON = eqJSON;
1764 exports.eqToString = eqToString;
1765 exports.expectTrue = createExpect(assertTrue);
1766 exports.expectFalse = createExpect(assertFalse);
1767 exports.expectGE = createExpect(assertGE);
1768 exports.expectGT = createExpect(assertGT);
1769 exports.expectEquals = createExpect(assertEquals);
1770 exports.expectLE = createExpect(assertLE);
1771 exports.expectLT = createExpect(assertLT);
1772 exports.expectNotEquals = createExpect(assertNotEquals);
1773 exports.expectNotReached = createExpect(assertNotReached);
1774 exports.expectAccessibilityOk = createExpect(assertAccessibilityOk);
1775 exports.invokeCallback = invokeCallback;
1776 exports.preloadJavascriptLibraries = preloadJavascriptLibraries;
1777 exports.registerMessageCallback = registerMessageCallback;
1778 exports.registerMockGlobals = registerMockGlobals;
1779 exports.registerMockMessageCallbacks = registerMockMessageCallbacks;
1780 exports.resetTestState = resetTestState;
1781 exports.runAccessibilityAudit = runAccessibilityAudit;
1782 exports.runAllActions = runAllActions;
1783 exports.runAllActionsAsync = runAllActionsAsync;
1784 exports.runTest = runTest;
1785 exports.runTestFunction = runTestFunction;
1786 exports.SaveMockArguments = SaveMockArguments;
1787 exports.DUMMY_URL = DUMMY_URL;
1788 exports.TEST = TEST;
1789 exports.TEST_F = TEST_F;
1790 exports.RUNTIME_TEST_F = TEST_F;
1791 exports.GEN = GEN;
1792 exports.GEN_INCLUDE = GEN_INCLUDE;
1793 exports.WhenTestDone = WhenTestDone;
1795 // Import the Mock4JS helpers.
1796 Mock4JS.addMockSupport(exports);
1797 })(this);