Best JavaScript code snippet using webdriverio-monorepo
mock-tests.js
Source:mock-tests.js
1YUI.add('mock-tests', function(Y) {2 var Assert = Y.Assert,3 ObjectAssert = Y.ObjectAssert;4 //-------------------------------------------------------------------------5 // Base Test Suite6 //-------------------------------------------------------------------------7 var suite = new Y.Test.Suite("Mock Tests");8 //-------------------------------------------------------------------------9 // Test Case for call count10 //-------------------------------------------------------------------------11 suite.add(new Y.Test.Case({12 name : "Call Count Tests",13 _should: {14 fail: {15 "Call count should default to 1 and fail": 1,16 "Call count set to 1 should fail when method isn't called": 1,17 "Call count set to 1 should fail when method is called twice": 1,18 "Call count set to 0 should fail when method is called once": 119 }20 },21 /*22 * Tests that leaving off callCount results in a callCount of 1, so23 * calling the mock method once should make the test pass.24 */25 "Call count should default to 1 and pass": function(){26 var mock = Y.Mock();27 Y.Mock.expect(mock, {28 method: "method"29 });30 mock.method();31 Y.Mock.verify(mock);32 },33 /*34 * Tests that leaving off callCount results in a callCount of 1, so35 * not calling the mock method once should make the test fail.36 */37 "Call count should default to 1 and fail": function(){38 var mock = Y.Mock();39 Y.Mock.expect(mock, {40 method: "method"41 });42 Y.Mock.verify(mock);43 },44 /*45 * Tests that setting callCount to 1 and46 * calling the mock method once should make the test pass.47 */48 "Call count set to 1 should pass when method is called once": function(){49 var mock = Y.Mock();50 Y.Mock.expect(mock, {51 method: "method",52 callCount: 153 });54 mock.method();55 Y.Mock.verify(mock);56 },57 /*58 * Tests that setting callCount to 1 and not59 * calling the mock method once should make the test fail.60 */61 "Call count set to 1 should fail when method isn't called": function(){62 var mock = Y.Mock();63 Y.Mock.expect(mock, {64 method: "method",65 callCount: 166 });67 Y.Mock.verify(mock);68 },69 /*70 * Tests that setting callCount to 1 and not71 * calling the mock method twice should make the test fail.72 */73 "Call count set to 1 should fail when method is called twice": function(){74 var mock = Y.Mock();75 Y.Mock.expect(mock, {76 method: "method",77 callCount: 178 });79 mock.method();80 mock.method();81 Y.Mock.verify(mock);82 },83 /*84 * Tests that setting callCount to 0 and85 * calling the mock method once should make the test fail.86 */87 "Call count set to 0 should fail when method is called once": function(){88 var mock = Y.Mock();89 Y.Mock.expect(mock, {90 method: "method",91 callCount: 092 });93 mock.method();94 Y.Mock.verify(mock);95 },96 /*97 * Tests that setting callCount to 0 and not98 * calling the mock method once should make the test pass.99 */100 "Call count set to 0 should pass when method isn't called": function(){101 var mock = Y.Mock();102 Y.Mock.expect(mock, {103 method: "method",104 callCount: 0105 });106 Y.Mock.verify(mock);107 }108 }));109 //-------------------------------------------------------------------------110 // Test Case for arguments111 //-------------------------------------------------------------------------112 suite.add(new Y.Test.Case({113 name : "Arguments Tests",114 _should: {115 fail: {116 "Passing an incorrect number of arguments should make the test fail": 1,117 "Passing an inexact argument should make the test fail" : 1,118 "Passing a number to an Boolean argument should make the test fail": 1,119 "Passing a string to an Boolean argument should make the test fail": 1,120 "Passing a object to an Boolean argument should make the test fail": 1,121 "Passing a function to an Boolean argument should make the test fail": 1,122 "Passing a null to an Boolean argument should make the test fail": 1,123 "Passing a number to an String argument should make the test fail": 1,124 "Passing a boolean to an String argument should make the test fail": 1,125 "Passing a object to an String argument should make the test fail": 1,126 "Passing a function to an String argument should make the test fail": 1,127 "Passing a null to an String argument should make the test fail": 1,128 "Passing a string to an Number argument should make the test fail": 1,129 "Passing a boolean to an Number argument should make the test fail": 1,130 "Passing a object to an Number argument should make the test fail": 1,131 "Passing a function to an Number argument should make the test fail": 1,132 "Passing a null to an Number argument should make the test fail": 1,133 "Passing a string to an Object argument should make the test fail": 1,134 "Passing a boolean to an Object argument should make the test fail": 1,135 "Passing a number to an Object argument should make the test fail": 1,136 "Passing a null to an Object argument should make the test fail": 1,137 "Passing a string to an Function argument should make the test fail": 1,138 "Passing a boolean to an Function argument should make the test fail": 1,139 "Passing a number to an Function argument should make the test fail": 1,140 "Passing a object to an Function argument should make the test fail": 1,141 "Passing a null to an Function argument should make the test fail": 1142 }143 },144 /*145 * Tests that when the number of arguments is verified, the test passes.146 */147 "Passing correct number of arguments should make the test pass": function(){148 var mock = Y.Mock();149 Y.Mock.expect(mock, {150 method: "method",151 args: [ Y.Mock.Value.Any ]152 });153 mock.method(1);154 Y.Mock.verify(mock);155 },156 /*157 * Tests that when the number of arguments is not verified, the test fails.158 */159 "Passing an incorrect number of arguments should make the test fail": function(){160 var mock = Y.Mock();161 Y.Mock.expect(mock, {162 method: "method",163 args: [ Y.Mock.Value.Any ]164 });165 mock.method(1, 2);166 Y.Mock.verify(mock);167 },168 /*169 * Tests that passing the exactly specified argument causes the test to pass.170 */171 "Passing the exact argument should make the test pass": function(){172 var arg = {};173 var mock = Y.Mock();174 Y.Mock.expect(mock, {175 method: "method",176 args: [ arg ]177 });178 mock.method(arg);179 Y.Mock.verify(mock);180 },181 /*182 * Tests that passing an argument that isn't exactly specified argument causes the test to fail.183 */184 "Passing an inexact argument should make the test fail": function(){185 var arg = {};186 var mock = Y.Mock();187 Y.Mock.expect(mock, {188 method: "method",189 args: [ arg ]190 });191 mock.method({});192 Y.Mock.verify(mock);193 },194 //Y.Mock.Value.Any tests --------------------------------------195 /*196 * Tests that passing a number to an argument specified as Y.Mock.Value.Any197 * results cause the test to pass.198 */199 "Passing a number to an Any argument should make the test pass": function(){200 var mock = Y.Mock();201 Y.Mock.expect(mock, {202 method: "method",203 args: [ Y.Mock.Value.Any ]204 });205 mock.method(1);206 Y.Mock.verify(mock);207 },208 /*209 * Tests that passing a boolean to an argument specified as Y.Mock.Value.Any210 * results cause the test to pass.211 */212 "Passing a boolean to an Any argument should make the test pass": function(){213 var mock = Y.Mock();214 Y.Mock.expect(mock, {215 method: "method",216 args: [ Y.Mock.Value.Any ]217 });218 mock.method(true);219 Y.Mock.verify(mock);220 },221 /*222 * Tests that passing a string to an argument specified as Y.Mock.Value.Any223 * results cause the test to pass.224 */225 "Passing a string to an Any argument should make the test pass": function(){226 var mock = Y.Mock();227 Y.Mock.expect(mock, {228 method: "method",229 args: [ Y.Mock.Value.Any ]230 });231 mock.method("");232 Y.Mock.verify(mock);233 },234 /*235 * Tests that passing an object to an argument specified as Y.Mock.Value.Any236 * results cause the test to pass.237 */238 "Passing a object to an Any argument should make the test pass": function(){239 var mock = Y.Mock();240 Y.Mock.expect(mock, {241 method: "method",242 args: [ Y.Mock.Value.Any ]243 });244 mock.method({});245 Y.Mock.verify(mock);246 },247 /*248 * Tests that passing a function to an argument specified as Y.Mock.Value.Any249 * results cause the test to pass.250 */251 "Passing a function to an Any argument should make the test pass": function(){252 var mock = Y.Mock();253 Y.Mock.expect(mock, {254 method: "method",255 args: [ Y.Mock.Value.Any ]256 });257 mock.method(function(){});258 Y.Mock.verify(mock);259 },260 /*261 * Tests that passing a null to an argument specified as Y.Mock.Value.Any262 * results cause the test to pass.263 */264 "Passing a null to an Any argument should make the test pass": function(){265 var mock = Y.Mock();266 Y.Mock.expect(mock, {267 method: "method",268 args: [ Y.Mock.Value.Any ]269 });270 mock.method(null);271 Y.Mock.verify(mock);272 },273 //Y.Mock.Value.Boolean tests --------------------------------------274 /*275 * Tests that passing a number to an argument specified as Y.Mock.Value.Boolean276 * results cause the test to fail.277 */278 "Passing a number to an Boolean argument should make the test fail": function(){279 var mock = Y.Mock();280 Y.Mock.expect(mock, {281 method: "method",282 args: [ Y.Mock.Value.Boolean ]283 });284 mock.method(1);285 Y.Mock.verify(mock);286 },287 /*288 * Tests that passing a boolean to an argument specified as Y.Mock.Value.Boolean289 * results cause the test to pass.290 */291 "Passing a boolean to an Boolean argument should make the test pass": function(){292 var mock = Y.Mock();293 Y.Mock.expect(mock, {294 method: "method",295 args: [ Y.Mock.Value.Boolean ]296 });297 mock.method(true);298 Y.Mock.verify(mock);299 },300 /*301 * Tests that passing a string to an argument specified as Y.Mock.Value.Boolean302 * results cause the test to fail.303 */304 "Passing a string to an Boolean argument should make the test fail": function(){305 var mock = Y.Mock();306 Y.Mock.expect(mock, {307 method: "method",308 args: [ Y.Mock.Value.Boolean ]309 });310 mock.method("");311 Y.Mock.verify(mock);312 },313 /*314 * Tests that passing an object to an argument specified as Y.Mock.Value.Boolean315 * results cause the test to fail.316 */317 "Passing a object to an Boolean argument should make the test fail": function(){318 var mock = Y.Mock();319 Y.Mock.expect(mock, {320 method: "method",321 args: [ Y.Mock.Value.Boolean ]322 });323 mock.method({});324 Y.Mock.verify(mock);325 },326 /*327 * Tests that passing a function to an argument specified as Y.Mock.Value.Boolean328 * results cause the test to fail.329 */330 "Passing a function to an Boolean argument should make the test fail": function(){331 var mock = Y.Mock();332 Y.Mock.expect(mock, {333 method: "method",334 args: [ Y.Mock.Value.Boolean ]335 });336 mock.method(function(){});337 Y.Mock.verify(mock);338 },339 /*340 * Tests that passing a null to an argument specified as Y.Mock.Value.Boolean341 * results cause the test to fail.342 */343 "Passing a null to an Boolean argument should make the test fail": function(){344 var mock = Y.Mock();345 Y.Mock.expect(mock, {346 method: "method",347 args: [ Y.Mock.Value.Boolean ]348 });349 mock.method(null);350 Y.Mock.verify(mock);351 },352 //Y.Mock.Value.String tests --------------------------------------353 /*354 * Tests that passing a number to an argument specified as Y.Mock.Value.String355 * results cause the test to fail.356 */357 "Passing a number to an String argument should make the test fail": function(){358 var mock = Y.Mock();359 Y.Mock.expect(mock, {360 method: "method",361 args: [ Y.Mock.Value.String ]362 });363 mock.method(1);364 Y.Mock.verify(mock);365 },366 /*367 * Tests that passing a boolean to an argument specified as Y.Mock.Value.String368 * results cause the test to fail.369 */370 "Passing a boolean to an String argument should make the test fail": function(){371 var mock = Y.Mock();372 Y.Mock.expect(mock, {373 method: "method",374 args: [ Y.Mock.Value.String ]375 });376 mock.method(true);377 Y.Mock.verify(mock);378 },379 /*380 * Tests that passing a string to an argument specified as Y.Mock.Value.String381 * results cause the test to pass.382 */383 "Passing a string to an String argument should make the test pass": function(){384 var mock = Y.Mock();385 Y.Mock.expect(mock, {386 method: "method",387 args: [ Y.Mock.Value.String ]388 });389 mock.method("");390 Y.Mock.verify(mock);391 },392 /*393 * Tests that passing an object to an argument specified as Y.Mock.Value.String394 * results cause the test to fail.395 */396 "Passing a object to an String argument should make the test fail": function(){397 var mock = Y.Mock();398 Y.Mock.expect(mock, {399 method: "method",400 args: [ Y.Mock.Value.String ]401 });402 mock.method({});403 Y.Mock.verify(mock);404 },405 /*406 * Tests that passing a function to an argument specified as Y.Mock.Value.String407 * results cause the test to fail.408 */409 "Passing a function to an String argument should make the test fail": function(){410 var mock = Y.Mock();411 Y.Mock.expect(mock, {412 method: "method",413 args: [ Y.Mock.Value.String ]414 });415 mock.method(function(){});416 Y.Mock.verify(mock);417 },418 /*419 * Tests that passing a null to an argument specified as Y.Mock.Value.String420 * results cause the test to fail.421 */422 "Passing a null to an String argument should make the test fail": function(){423 var mock = Y.Mock();424 Y.Mock.expect(mock, {425 method: "method",426 args: [ Y.Mock.Value.String ]427 });428 mock.method(null);429 Y.Mock.verify(mock);430 },431 //Y.Mock.Value.Number tests --------------------------------------432 /*433 * Tests that passing a number to an argument specified as Y.Mock.Value.Number434 * results cause the test to pass.435 */436 "Passing a number to an Number argument should make the test pass": function(){437 var mock = Y.Mock();438 Y.Mock.expect(mock, {439 method: "method",440 args: [ Y.Mock.Value.Number ]441 });442 mock.method(1);443 Y.Mock.verify(mock);444 },445 /*446 * Tests that passing a boolean to an argument specified as Y.Mock.Value.Number447 * results cause the test to fail.448 */449 "Passing a boolean to an Number argument should make the test fail": function(){450 var mock = Y.Mock();451 Y.Mock.expect(mock, {452 method: "method",453 args: [ Y.Mock.Value.Number ]454 });455 mock.method(true);456 Y.Mock.verify(mock);457 },458 /*459 * Tests that passing a string to an argument specified as Y.Mock.Value.Number460 * results cause the test to fail.461 */462 "Passing a string to an Number argument should make the test fail": function(){463 var mock = Y.Mock();464 Y.Mock.expect(mock, {465 method: "method",466 args: [ Y.Mock.Value.Number ]467 });468 mock.method("");469 Y.Mock.verify(mock);470 },471 /*472 * Tests that passing an object to an argument specified as Y.Mock.Value.Number473 * results cause the test to fail.474 */475 "Passing a object to an Number argument should make the test fail": function(){476 var mock = Y.Mock();477 Y.Mock.expect(mock, {478 method: "method",479 args: [ Y.Mock.Value.Number ]480 });481 mock.method({});482 Y.Mock.verify(mock);483 },484 /*485 * Tests that passing a function to an argument specified as Y.Mock.Value.Number486 * results cause the test to fail.487 */488 "Passing a function to an Number argument should make the test fail": function(){489 var mock = Y.Mock();490 Y.Mock.expect(mock, {491 method: "method",492 args: [ Y.Mock.Value.Number ]493 });494 mock.method(function(){});495 Y.Mock.verify(mock);496 },497 /*498 * Tests that passing a null to an argument specified as Y.Mock.Value.Number499 * results cause the test to fail.500 */501 "Passing a null to an Number argument should make the test fail": function(){502 var mock = Y.Mock();503 Y.Mock.expect(mock, {504 method: "method",505 args: [ Y.Mock.Value.Number ]506 });507 mock.method(null);508 Y.Mock.verify(mock);509 },510 //Y.Mock.Value.Function tests --------------------------------------511 /*512 * Tests that passing a number to an argument specified as Y.Mock.Value.Function513 * results cause the test to fail.514 */515 "Passing a number to an Function argument should make the test fail": function(){516 var mock = Y.Mock();517 Y.Mock.expect(mock, {518 method: "method",519 args: [ Y.Mock.Value.Function ]520 });521 mock.method(1);522 Y.Mock.verify(mock);523 },524 /*525 * Tests that passing a boolean to an argument specified as Y.Mock.Value.Function526 * results cause the test to fail.527 */528 "Passing a boolean to an Function argument should make the test fail": function(){529 var mock = Y.Mock();530 Y.Mock.expect(mock, {531 method: "method",532 args: [ Y.Mock.Value.Function ]533 });534 mock.method(true);535 Y.Mock.verify(mock);536 },537 /*538 * Tests that passing a string to an argument specified as Y.Mock.Value.Function539 * results cause the test to fail.540 */541 "Passing a string to an Function argument should make the test fail": function(){542 var mock = Y.Mock();543 Y.Mock.expect(mock, {544 method: "method",545 args: [ Y.Mock.Value.Function ]546 });547 mock.method("");548 Y.Mock.verify(mock);549 },550 /*551 * Tests that passing an object to an argument specified as Y.Mock.Value.Function552 * results cause the test to fail.553 */554 "Passing a object to an Function argument should make the test fail": function(){555 var mock = Y.Mock();556 Y.Mock.expect(mock, {557 method: "method",558 args: [ Y.Mock.Value.Function ]559 });560 mock.method({});561 Y.Mock.verify(mock);562 },563 /*564 * Tests that passing a function to an argument specified as Y.Mock.Value.Function565 * results cause the test to pass.566 */567 "Passing a function to an Function argument should make the test pass": function(){568 var mock = Y.Mock();569 Y.Mock.expect(mock, {570 method: "method",571 args: [ Y.Mock.Value.Function ]572 });573 mock.method(function(){});574 Y.Mock.verify(mock);575 },576 /*577 * Tests that passing a null to an argument specified as Y.Mock.Value.Function578 * results cause the test to fail.579 */580 "Passing a null to an Function argument should make the test fail": function(){581 var mock = Y.Mock();582 Y.Mock.expect(mock, {583 method: "method",584 args: [ Y.Mock.Value.Function ]585 });586 mock.method(null);587 Y.Mock.verify(mock);588 },589 //Y.Mock.Value.Object tests --------------------------------------590 /*591 * Tests that passing a number to an argument specified as Y.Mock.Value.Object592 * results cause the test to fail.593 */594 "Passing a number to an Object argument should make the test fail": function(){595 var mock = Y.Mock();596 Y.Mock.expect(mock, {597 method: "method",598 args: [ Y.Mock.Value.Object ]599 });600 mock.method(1);601 Y.Mock.verify(mock);602 },603 /*604 * Tests that passing a boolean to an argument specified as Y.Mock.Value.Object605 * results cause the test to fail.606 */607 "Passing a boolean to an Object argument should make the test fail": function(){608 var mock = Y.Mock();609 Y.Mock.expect(mock, {610 method: "method",611 args: [ Y.Mock.Value.Object ]612 });613 mock.method(true);614 Y.Mock.verify(mock);615 },616 /*617 * Tests that passing a string to an argument specified as Y.Mock.Value.Object618 * results cause the test to fail.619 */620 "Passing a string to an Object argument should make the test fail": function(){621 var mock = Y.Mock();622 Y.Mock.expect(mock, {623 method: "method",624 args: [ Y.Mock.Value.Object ]625 });626 mock.method("");627 Y.Mock.verify(mock);628 },629 /*630 * Tests that passing an object to an argument specified as Y.Mock.Value.Object631 * results cause the test to pass.632 */633 "Passing a object to an Object argument should make the test pass": function(){634 var mock = Y.Mock();635 Y.Mock.expect(mock, {636 method: "method",637 args: [ Y.Mock.Value.Object ]638 });639 mock.method({});640 Y.Mock.verify(mock);641 },642 /*643 * Tests that passing a function to an argument specified as Y.Mock.Value.Object644 * results cause the test to pass.645 */646 "Passing a function to an Object argument should make the test pass": function(){647 var mock = Y.Mock();648 Y.Mock.expect(mock, {649 method: "method",650 args: [ Y.Mock.Value.Object ]651 });652 mock.method(function(){});653 Y.Mock.verify(mock);654 },655 /*656 * Tests that passing a null to an argument specified as Y.Mock.Value.Object657 * results cause the test to fail.658 */659 "Passing a null to an Object argument should make the test fail": function(){660 var mock = Y.Mock();661 Y.Mock.expect(mock, {662 method: "method",663 args: [ Y.Mock.Value.Object ]664 });665 mock.method(null);666 Y.Mock.verify(mock);667 }668 }));669 //-------------------------------------------------------------------------670 // Test Case for asynchronous mock calls671 //-------------------------------------------------------------------------672 suite.add(new Y.Test.Case({673 name : "Asynchronous Tests",674 _should: {675 fail: {676 "A mock method called asynchronously shouldn't cause an error": 1677 }678 },679 /*680 * Tests that when a mock method is called asynchronously, either via681 * timeout or XHR callback, that its error is properly handled and682 * the failure is logged to the test.683 */684 "A mock method called asynchronously shouldn't cause an error": function(){685 var mock = Y.Mock();686 Y.Mock.expect(mock, {687 method: "method",688 args: [ Y.Mock.Value.String ]689 });690 setTimeout(function(){691 mock.method(null);692 }, 250);693 this.wait(function(){694 Y.Mock.verify(mock);695 }, 500);696 }697 }));698 //-------------------------------------------------------------------------699 // Test Case for returns expectations700 //-------------------------------------------------------------------------701 suite.add(new Y.Test.Case({702 name : "Returns Tests",703 groups: ["mock", "common"],704 /*705 * Test that when no 'returns' expectation is given it is undefined.706 */707 "Value for 'returns' should default to undefined": function(){708 var mock = Y.Test.Mock(),709 result;710 Y.Test.Mock.expect(mock, {711 method: "method"712 });713 result = mock.method();714 Assert.isUndefined(result);715 },716 /*717 * Test that when a 'returns' expectation is given it is used.718 */719 "Value for 'returns' should be used as return value": function(){720 var mock = Y.Test.Mock(),721 result;722 Y.Test.Mock.expect(mock, {723 method: "method",724 returns: true725 });726 result = mock.method();727 Assert.isTrue(result);728 },729 /*730 * Test that when a 'returns' expectation is given it is used regardless731 * of the return value of any run function provided.732 */733 "Value for 'returns' should be used rather than run value": function(){734 var mock = Y.Test.Mock(),735 result;736 Y.Test.Mock.expect(mock, {737 method: "method",738 returns: true,739 run: function() {740 return false;741 }742 });743 result = mock.method();744 Assert.isTrue(result);745 }746 }));747 //-------------------------------------------------------------------------748 // Test Case for run expectations749 //-------------------------------------------------------------------------750 suite.add(new Y.Test.Case({751 name : "Run Tests",752 groups: ["mock", "common"],753 /*754 * Test that when run is given it is executed.755 */756 "A supplied run function should be invoked": function(){757 var mock = Y.Test.Mock(),758 invoked = false;759 Y.Test.Mock.expect(mock, {760 method: "method",761 run: function() {762 invoked = true;763 }764 });765 mock.method();766 Assert.isTrue(invoked);767 },768 /*769 * Test that run function return value is used when no 'returns' key is770 * present.771 */772 "A supplied run function's return value should be used.": function(){773 var mock = Y.Test.Mock(),774 result;775 Y.Test.Mock.expect(mock, {776 method: "method",777 run: function() {778 return 'invoked';779 }780 });781 result = mock.method();782 Assert.areEqual(result, 'invoked');783 }784 }));785 Y.Test.Runner.add(suite);...
mockclassfactory.js
Source:mockclassfactory.js
1// Copyright 2008 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview This file defines a factory that can be used to mock and16 * replace an entire class. This allows for mocks to be used effectively with17 * "new" instead of having to inject all instances. Essentially, a given class18 * is replaced with a proxy to either a loose or strict mock. Proxies locate19 * the appropriate mock based on constructor arguments.20 *21 * The usage is:22 * <ul>23 * <li>Create a mock with one of the provided methods with a specifc set of24 * constructor arguments25 * <li>Set expectations by calling methods on the mock object26 * <li>Call $replay() on the mock object27 * <li>Instantiate the object as normal28 * <li>Call $verify() to make sure that expectations were met29 * <li>Call reset on the factory to revert all classes back to their original30 * state31 * </ul>32 *33 * For examples, please see the unit test.34 *35 */36goog.provide('goog.testing.MockClassFactory');37goog.provide('goog.testing.MockClassRecord');38goog.require('goog.array');39goog.require('goog.object');40goog.require('goog.testing.LooseMock');41goog.require('goog.testing.StrictMock');42goog.require('goog.testing.TestCase');43goog.require('goog.testing.mockmatchers');44/**45 * A record that represents all the data associated with a mock replacement of46 * a given class.47 * @param {Object} namespace The namespace in which the mocked class resides.48 * @param {string} className The name of the class within the namespace.49 * @param {Function} originalClass The original class implementation before it50 * was replaced by a proxy.51 * @param {Function} proxy The proxy that replaced the original class.52 * @constructor53 */54goog.testing.MockClassRecord = function(namespace, className, originalClass,55 proxy) {56 /**57 * A standard closure namespace (e.g. goog.foo.bar) that contains the mock58 * class referenced by this MockClassRecord.59 * @type {Object}60 * @private61 */62 this.namespace_ = namespace;63 /**64 * The name of the class within the provided namespace.65 * @type {string}66 * @private67 */68 this.className_ = className;69 /**70 * The original class implementation.71 * @type {Function}72 * @private73 */74 this.originalClass_ = originalClass;75 /**76 * The proxy being used as a replacement for the original class.77 * @type {Function}78 * @private79 */80 this.proxy_ = proxy;81 /**82 * A mocks that will be constructed by their argument list. The entries are83 * objects with the format {'args': args, 'mock': mock}.84 * @type {Array.<Object>}85 * @private86 */87 this.instancesByArgs_ = [];88};89/**90 * A mock associated with the static functions for a given class.91 * @type {goog.testing.StrictMock|goog.testing.LooseMock|null}92 * @private93 */94goog.testing.MockClassRecord.prototype.staticMock_ = null;95/**96 * A getter for this record's namespace.97 * @return {Object} The namespace.98 */99goog.testing.MockClassRecord.prototype.getNamespace = function() {100 return this.namespace_;101};102/**103 * A getter for this record's class name.104 * @return {string} The name of the class referenced by this record.105 */106goog.testing.MockClassRecord.prototype.getClassName = function() {107 return this.className_;108};109/**110 * A getter for the original class.111 * @return {Function} The original class implementation before mocking.112 */113goog.testing.MockClassRecord.prototype.getOriginalClass = function() {114 return this.originalClass_;115};116/**117 * A getter for the proxy being used as a replacement for the original class.118 * @return {Function} The proxy.119 */120goog.testing.MockClassRecord.prototype.getProxy = function() {121 return this.proxy_;122};123/**124 * A getter for the static mock.125 * @return {goog.testing.StrictMock|goog.testing.LooseMock|null} The static126 * mock associated with this record.127 */128goog.testing.MockClassRecord.prototype.getStaticMock = function() {129 return this.staticMock_;130};131/**132 * A setter for the static mock.133 * @param {goog.testing.StrictMock|goog.testing.LooseMock} staticMock A mock to134 * associate with the static functions for the referenced class.135 */136goog.testing.MockClassRecord.prototype.setStaticMock = function(staticMock) {137 this.staticMock_ = staticMock;138};139/**140 * Adds a new mock instance mapping. The mapping connects a set of function141 * arguments to a specific mock instance.142 * @param {Array} args An array of function arguments.143 * @param {goog.testing.StrictMock|goog.testing.LooseMock} mock A mock144 * associated with the supplied arguments.145 */146goog.testing.MockClassRecord.prototype.addMockInstance = function(args, mock) {147 this.instancesByArgs_.push({args: args, mock: mock});148};149/**150 * Finds the mock corresponding to a given argument set. Throws an error if151 * there is no appropriate match found.152 * @param {Array} args An array of function arguments.153 * @return {goog.testing.StrictMock|goog.testing.LooseMock|null} The mock154 * corresponding to a given argument set.155 */156goog.testing.MockClassRecord.prototype.findMockInstance = function(args) {157 for (var i = 0; i < this.instancesByArgs_.length; i++) {158 var instanceArgs = this.instancesByArgs_[i].args;159 if (goog.testing.mockmatchers.flexibleArrayMatcher(instanceArgs, args)) {160 return this.instancesByArgs_[i].mock;161 }162 }163 return null;164};165/**166 * Resets this record by reverting all the mocked classes back to the original167 * implementation and clearing out the mock instance list.168 */169goog.testing.MockClassRecord.prototype.reset = function() {170 this.namespace_[this.className_] = this.originalClass_;171 this.instancesByArgs_ = [];172};173/**174 * A factory used to create new mock class instances. It is able to generate175 * both static and loose mocks. The MockClassFactory is a singleton since it176 * tracks the classes that have been mocked internally.177 * @constructor178 */179goog.testing.MockClassFactory = function() {180 if (goog.testing.MockClassFactory.instance_) {181 return goog.testing.MockClassFactory.instance_;182 }183 /**184 * A map from class name -> goog.testing.MockClassRecord.185 * @type {Object}186 * @private187 */188 this.mockClassRecords_ = {};189 goog.testing.MockClassFactory.instance_ = this;190};191/**192 * A singleton instance of the MockClassFactory.193 * @type {goog.testing.MockClassFactory?}194 * @private195 */196goog.testing.MockClassFactory.instance_ = null;197/**198 * The names of the fields that are defined on Object.prototype.199 * @type {Array.<string>}200 * @private201 */202goog.testing.MockClassFactory.PROTOTYPE_FIELDS_ = [203 'constructor',204 'hasOwnProperty',205 'isPrototypeOf',206 'propertyIsEnumerable',207 'toLocaleString',208 'toString',209 'valueOf'210];211/**212 * Iterates through a namespace to find the name of a given class. This is done213 * solely to support compilation since string identifiers would break down.214 * Tests usually aren't compiled, but the functionality is supported.215 * @param {Object} namespace A javascript namespace (e.g. goog.testing).216 * @param {Function} classToMock The class whose name should be returned.217 * @return {string} The name of the class.218 * @private219 */220goog.testing.MockClassFactory.prototype.getClassName_ = function(namespace,221 classToMock) {222 if (namespace === goog.global) {223 namespace = goog.testing.TestCase.getGlobals();224 }225 for (var prop in namespace) {226 if (namespace[prop] === classToMock) {227 return prop;228 }229 }230 throw Error('Class is not a part of the given namespace');231};232/**233 * Returns whether or not a given class has been mocked.234 * @param {string} className The name of the class.235 * @return {boolean} Whether or not the given class name has a MockClassRecord.236 * @private237 */238goog.testing.MockClassFactory.prototype.classHasMock_ = function(className) {239 return !!this.mockClassRecords_[className];240};241/**242 * Returns a proxy constructor closure. Since this is a constructor, "this"243 * refers to the local scope of the constructed object thus bind cannot be244 * used.245 * @param {string} className The name of the class.246 * @param {Function} mockFinder A bound function that returns the mock247 * associated with a class given the constructor's argument list.248 * @return {Function} A proxy constructor.249 * @private250 */251goog.testing.MockClassFactory.prototype.getProxyCtor_ = function(className,252 mockFinder) {253 return function() {254 this.$mock_ = mockFinder(className, arguments);255 if (!this.$mock_) {256 // The "arguments" variable is not a proper Array so it must be converted.257 var args = Array.prototype.slice.call(arguments, 0);258 throw Error('No mock found for ' + className + ' with arguments ' +259 args.join(', '));260 }261 };262};263/**264 * Returns a proxy function for a mock class instance. This function cannot265 * be used with bind since "this" must refer to the scope of the proxy266 * constructor.267 * @param {string} fnName The name of the function that should be proxied.268 * @return {Function} A proxy function.269 * @private270 */271goog.testing.MockClassFactory.prototype.getProxyFunction_ = function(fnName) {272 return function() {273 return this.$mock_[fnName].apply(this.$mock_, arguments);274 };275};276/**277 * Find a mock instance for a given class name and argument list.278 * @param {string} className The name of the class.279 * @param {Array} args The argument list to match.280 * @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock found for281 * the given argument list.282 * @private283 */284goog.testing.MockClassFactory.prototype.findMockInstance_ = function(className,285 args) {286 return this.mockClassRecords_[className].findMockInstance(args);287};288/**289 * Create a proxy class. A proxy will pass functions to the mock for a class.290 * The proxy class only covers prototype methods. A static mock is not build291 * simultaneously since it might be strict or loose. The proxy class inherits292 * from the target class in order to preserve instanceof checks.293 * @param {Object} namespace A javascript namespace (e.g. goog.testing).294 * @param {Function} classToMock The class that will be proxied.295 * @param {string} className The name of the class.296 * @return {Function} The proxy for provided class.297 * @private298 */299goog.testing.MockClassFactory.prototype.createProxy_ = function(namespace,300 classToMock, className) {301 var proxy = this.getProxyCtor_(className,302 goog.bind(this.findMockInstance_, this));303 var protoToProxy = classToMock.prototype;304 goog.inherits(proxy, classToMock);305 for (var prop in protoToProxy) {306 if (goog.isFunction(protoToProxy[prop])) {307 proxy.prototype[prop] = this.getProxyFunction_(prop);308 }309 }310 // For IE the for-in-loop does not contain any properties that are not311 // enumerable on the prototype object (for example isPrototypeOf from312 // Object.prototype) and it will also not include 'replace' on objects that313 // extend String and change 'replace' (not that it is common for anyone to314 // extend anything except Object).315 // TODO (arv): Implement goog.object.getIterator and replace this loop.316 goog.array.forEach(goog.testing.MockClassFactory.PROTOTYPE_FIELDS_,317 function(field) {318 if (Object.prototype.hasOwnProperty.call(protoToProxy, field)) {319 proxy.prototype[field] = this.getProxyFunction_(field);320 }321 }, this);322 this.mockClassRecords_[className] = new goog.testing.MockClassRecord(323 namespace, className, classToMock, proxy);324 namespace[className] = proxy;325 return proxy;326};327/**328 * Gets either a loose or strict mock for a given class based on a set of329 * arguments.330 * @param {Object} namespace A javascript namespace (e.g. goog.testing).331 * @param {Function} classToMock The class that will be mocked.332 * @param {boolean} isStrict Whether or not the mock should be strict.333 * @param {Array} ctorArgs The arguments associated with this instance's334 * constructor.335 * @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock created336 * for the provided class.337 * @private338 */339goog.testing.MockClassFactory.prototype.getMockClass_ =340 function(namespace, classToMock, isStrict, ctorArgs) {341 var className = this.getClassName_(namespace, classToMock);342 // The namespace and classToMock variables should be removed from the343 // passed in argument stack.344 ctorArgs = goog.array.slice(ctorArgs, 2);345 if (goog.isFunction(classToMock)) {346 var mock = isStrict ? new goog.testing.StrictMock(classToMock) :347 new goog.testing.LooseMock(classToMock);348 if (!this.classHasMock_(className)) {349 this.createProxy_(namespace, classToMock, className);350 } else {351 var instance = this.findMockInstance_(className, ctorArgs);352 if (instance) {353 throw Error('Mock instance already created for ' + className +354 ' with arguments ' + ctorArgs.join(', '));355 }356 }357 this.mockClassRecords_[className].addMockInstance(ctorArgs, mock);358 return mock;359 } else {360 throw Error('Cannot create a mock class for ' + className +361 ' of type ' + typeof classToMock);362 }363};364/**365 * Gets a strict mock for a given class.366 * @param {Object} namespace A javascript namespace (e.g. goog.testing).367 * @param {Function} classToMock The class that will be mocked.368 * @param {...*} var_args The arguments associated with this instance's369 * constructor.370 * @return {goog.testing.StrictMock} The mock created for the provided class.371 */372goog.testing.MockClassFactory.prototype.getStrictMockClass =373 function(namespace, classToMock, var_args) {374 var args = /** @type {Array} */ (arguments);375 return /** @type {goog.testing.StrictMock} */ (this.getMockClass_(namespace,376 classToMock, true, args));377};378/**379 * Gets a loose mock for a given class.380 * @param {Object} namespace A javascript namespace (e.g. goog.testing).381 * @param {Function} classToMock The class that will be mocked.382 * @param {...*} var_args The arguments associated with this instance's383 * constructor.384 * @return {goog.testing.LooseMock} The mock created for the provided class.385 */386goog.testing.MockClassFactory.prototype.getLooseMockClass =387 function(namespace, classToMock, var_args) {388 var args = /** @type {Array} */ (arguments);389 return /** @type {goog.testing.LooseMock} */ (this.getMockClass_(namespace,390 classToMock, false, args));391};392/**393 * Creates either a loose or strict mock for the static functions of a given394 * class.395 * @param {Function} classToMock The class whose static functions will be396 * mocked. This should be the original class and not the proxy.397 * @param {string} className The name of the class.398 * @param {Function} proxy The proxy that will replace the original class.399 * @param {boolean} isStrict Whether or not the mock should be strict.400 * @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock created401 * for the static functions of the provided class.402 * @private403 */404goog.testing.MockClassFactory.prototype.createStaticMock_ =405 function(classToMock, className, proxy, isStrict) {406 var mock = isStrict ? new goog.testing.StrictMock(classToMock, true) :407 new goog.testing.LooseMock(classToMock, false, true);408 for (var prop in classToMock) {409 if (goog.isFunction(classToMock[prop])) {410 proxy[prop] = goog.bind(mock.$mockMethod, mock, prop);411 } else if (classToMock[prop] !== classToMock.prototype) {412 proxy[prop] = classToMock[prop];413 }414 }415 this.mockClassRecords_[className].setStaticMock(mock);416 return mock;417};418/**419 * Gets either a loose or strict mock for the static functions of a given class.420 * @param {Object} namespace A javascript namespace (e.g. goog.testing).421 * @param {Function} classToMock The class whose static functions will be422 * mocked. This should be the original class and not the proxy.423 * @param {boolean} isStrict Whether or not the mock should be strict.424 * @return {goog.testing.StrictMock|goog.testing.LooseMock} The mock created425 * for the static functions of the provided class.426 * @private427 */428goog.testing.MockClassFactory.prototype.getStaticMock_ = function(namespace,429 classToMock, isStrict) {430 var className = this.getClassName_(namespace, classToMock);431 if (goog.isFunction(classToMock)) {432 if (!this.classHasMock_(className)) {433 var proxy = this.createProxy_(namespace, classToMock, className);434 var mock = this.createStaticMock_(classToMock, className, proxy,435 isStrict);436 return mock;437 }438 if (!this.mockClassRecords_[className].getStaticMock()) {439 var proxy = this.mockClassRecords_[className].getProxy();440 var originalClass = this.mockClassRecords_[className].getOriginalClass();441 var mock = this.createStaticMock_(originalClass, className, proxy,442 isStrict);443 return mock;444 } else {445 var mock = this.mockClassRecords_[className].getStaticMock();446 var mockIsStrict = mock instanceof goog.testing.StrictMock;447 if (mockIsStrict != isStrict) {448 var mockType = mock instanceof goog.testing.StrictMock ? 'strict' :449 'loose';450 var requestedType = isStrict ? 'strict' : 'loose';451 throw Error('Requested a ' + requestedType + ' static mock, but a ' +452 mockType + ' mock already exists.');453 }454 return mock;455 }456 } else {457 throw Error('Cannot create a mock for the static functions of ' +458 className + ' of type ' + typeof classToMock);459 }460};461/**462 * Gets a strict mock for the static functions of a given class.463 * @param {Object} namespace A javascript namespace (e.g. goog.testing).464 * @param {Function} classToMock The class whose static functions will be465 * mocked. This should be the original class and not the proxy.466 * @return {goog.testing.StrictMock} The mock created for the static functions467 * of the provided class.468 */469goog.testing.MockClassFactory.prototype.getStrictStaticMock =470 function(namespace, classToMock) {471 return /** @type {goog.testing.StrictMock} */ (this.getStaticMock_(namespace,472 classToMock, true));473};474/**475 * Gets a loose mock for the static functions of a given class.476 * @param {Object} namespace A javascript namespace (e.g. goog.testing).477 * @param {Function} classToMock The class whose static functions will be478 * mocked. This should be the original class and not the proxy.479 * @return {goog.testing.LooseMock} The mock created for the static functions480 * of the provided class.481 */482goog.testing.MockClassFactory.prototype.getLooseStaticMock =483 function(namespace, classToMock) {484 return /** @type {goog.testing.LooseMock} */ (this.getStaticMock_(namespace,485 classToMock, false));486};487/**488 * Resests the factory by reverting all mocked classes to their original489 * implementations and removing all MockClassRecords.490 */491goog.testing.MockClassFactory.prototype.reset = function() {492 goog.object.forEach(this.mockClassRecords_, function(record) {493 record.reset();494 });495 this.mockClassRecords_ = {};...
jquery.mockjax.js
Source:jquery.mockjax.js
1/*!2 * MockJax - jQuery Plugin to Mock Ajax requests3 *4 * Version: 1.5.35 * Released:6 * Home: http://github.com/appendto/jquery-mockjax7 * Author: Jonathan Sharp (http://jdsharp.com)8 * License: MIT,GPL9 *10 * Copyright (c) 2011 appendTo LLC.11 * Dual licensed under the MIT or GPL licenses.12 * http://appendto.com/open-source-licenses13 */14(function($) {15 var _ajax = $.ajax,16 mockHandlers = [],17 mockedAjaxCalls = [],18 CALLBACK_REGEX = /=\?(&|$)/,19 jsc = (new Date()).getTime();20 // Parse the given XML string.21 function parseXML(xml) {22 if ( window.DOMParser == undefined && window.ActiveXObject ) {23 DOMParser = function() { };24 DOMParser.prototype.parseFromString = function( xmlString ) {25 var doc = new ActiveXObject('Microsoft.XMLDOM');26 doc.async = 'false';27 doc.loadXML( xmlString );28 return doc;29 };30 }31 try {32 var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );33 if ( $.isXMLDoc( xmlDoc ) ) {34 var err = $('parsererror', xmlDoc);35 if ( err.length == 1 ) {36 throw('Error: ' + $(xmlDoc).text() );37 }38 } else {39 throw('Unable to parse XML');40 }41 return xmlDoc;42 } catch( e ) {43 var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );44 $(document).trigger('xmlParseError', [ msg ]);45 return undefined;46 }47 }48 // Trigger a jQuery event49 function trigger(s, type, args) {50 (s.context ? $(s.context) : $.event).trigger(type, args);51 }52 // Check if the data field on the mock handler and the request match. This53 // can be used to restrict a mock handler to being used only when a certain54 // set of data is passed to it.55 function isMockDataEqual( mock, live ) {56 var identical = true;57 // Test for situations where the data is a querystring (not an object)58 if (typeof live === 'string') {59 // Querystring may be a regex60 return $.isFunction( mock.test ) ? mock.test(live) : mock == live;61 }62 $.each(mock, function(k) {63 if ( live[k] === undefined ) {64 identical = false;65 return identical;66 } else {67 // This will allow to compare Arrays68 if ( typeof live[k] === 'object' && live[k] !== null ) {69 identical = identical && isMockDataEqual(mock[k], live[k]);70 } else {71 if ( mock[k] && $.isFunction( mock[k].test ) ) {72 identical = identical && mock[k].test(live[k]);73 } else {74 identical = identical && ( mock[k] == live[k] );75 }76 }77 }78 });79 return identical;80 }81 // See if a mock handler property matches the default settings82 function isDefaultSetting(handler, property) {83 return handler[property] === $.mockjaxSettings[property];84 }85 // Check the given handler should mock the given request86 function getMockForRequest( handler, requestSettings ) {87 // If the mock was registered with a function, let the function decide if we88 // want to mock this request89 if ( $.isFunction(handler) ) {90 return handler( requestSettings );91 }92 // Inspect the URL of the request and check if the mock handler's url93 // matches the url for this ajax request94 if ( $.isFunction(handler.url.test) ) {95 // The user provided a regex for the url, test it96 if ( !handler.url.test( requestSettings.url ) ) {97 return null;98 }99 } else {100 // Look for a simple wildcard '*' or a direct URL match101 var star = handler.url.indexOf('*');102 if (handler.url !== requestSettings.url && star === -1 ||103 !new RegExp(handler.url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, "\\$&").replace(/\*/g, '.+')).test(requestSettings.url)) {104 return null;105 }106 }107 // Inspect the data submitted in the request (either POST body or GET query string)108 if ( handler.data && requestSettings.data ) {109 if ( !isMockDataEqual(handler.data, requestSettings.data) ) {110 // They're not identical, do not mock this request111 return null;112 }113 }114 // Inspect the request type115 if ( handler && handler.type &&116 handler.type.toLowerCase() != requestSettings.type.toLowerCase() ) {117 // The request type doesn't match (GET vs. POST)118 return null;119 }120 return handler;121 }122 // Process the xhr objects send operation123 function _xhrSend(mockHandler, requestSettings, origSettings) {124 // This is a substitute for < 1.4 which lacks $.proxy125 var process = (function(that) {126 return function() {127 return (function() {128 var onReady;129 // The request has returned130 this.status = mockHandler.status;131 this.statusText = mockHandler.statusText;132 this.readyState = 4;133 // We have an executable function, call it to give134 // the mock handler a chance to update it's data135 if ( $.isFunction(mockHandler.response) ) {136 mockHandler.response(origSettings);137 }138 // Copy over our mock to our xhr object before passing control back to139 // jQuery's onreadystatechange callback140 if ( requestSettings.dataType == 'json' && ( typeof mockHandler.responseText == 'object' ) ) {141 this.responseText = JSON.stringify(mockHandler.responseText);142 } else if ( requestSettings.dataType == 'xml' ) {143 if ( typeof mockHandler.responseXML == 'string' ) {144 this.responseXML = parseXML(mockHandler.responseXML);145 //in jQuery 1.9.1+, responseXML is processed differently and relies on responseText146 this.responseText = mockHandler.responseXML;147 } else {148 this.responseXML = mockHandler.responseXML;149 }150 } else {151 this.responseText = mockHandler.responseText;152 }153 if( typeof mockHandler.status == 'number' || typeof mockHandler.status == 'string' ) {154 this.status = mockHandler.status;155 }156 if( typeof mockHandler.statusText === "string") {157 this.statusText = mockHandler.statusText;158 }159 // jQuery 2.0 renamed onreadystatechange to onload160 onReady = this.onreadystatechange || this.onload;161 // jQuery < 1.4 doesn't have onreadystate change for xhr162 if ( $.isFunction( onReady ) ) {163 if( mockHandler.isTimeout) {164 this.status = -1;165 }166 onReady.call( this, mockHandler.isTimeout ? 'timeout' : undefined );167 } else if ( mockHandler.isTimeout ) {168 // Fix for 1.3.2 timeout to keep success from firing.169 this.status = -1;170 }171 }).apply(that);172 };173 })(this);174 if ( mockHandler.proxy ) {175 // We're proxying this request and loading in an external file instead176 _ajax({177 global: false,178 url: mockHandler.proxy,179 type: mockHandler.proxyType,180 data: mockHandler.data,181 dataType: requestSettings.dataType === "script" ? "text/plain" : requestSettings.dataType,182 complete: function(xhr) {183 mockHandler.responseXML = xhr.responseXML;184 mockHandler.responseText = xhr.responseText;185 // Don't override the handler status/statusText if it's specified by the config186 if (isDefaultSetting(mockHandler, 'status')) {187 mockHandler.status = xhr.status;188 }189 if (isDefaultSetting(mockHandler, 'statusText')) {190 mockHandler.statusText = xhr.statusText;191 }192 this.responseTimer = setTimeout(process, mockHandler.responseTime || 0);193 }194 });195 } else {196 // type == 'POST' || 'GET' || 'DELETE'197 if ( requestSettings.async === false ) {198 // TODO: Blocking delay199 process();200 } else {201 this.responseTimer = setTimeout(process, mockHandler.responseTime || 50);202 }203 }204 }205 // Construct a mocked XHR Object206 function xhr(mockHandler, requestSettings, origSettings, origHandler) {207 // Extend with our default mockjax settings208 mockHandler = $.extend(true, {}, $.mockjaxSettings, mockHandler);209 if (typeof mockHandler.headers === 'undefined') {210 mockHandler.headers = {};211 }212 if ( mockHandler.contentType ) {213 mockHandler.headers['content-type'] = mockHandler.contentType;214 }215 return {216 status: mockHandler.status,217 statusText: mockHandler.statusText,218 readyState: 1,219 open: function() { },220 send: function() {221 origHandler.fired = true;222 _xhrSend.call(this, mockHandler, requestSettings, origSettings);223 },224 abort: function() {225 clearTimeout(this.responseTimer);226 },227 setRequestHeader: function(header, value) {228 mockHandler.headers[header] = value;229 },230 getResponseHeader: function(header) {231 // 'Last-modified', 'Etag', 'content-type' are all checked by jQuery232 if ( mockHandler.headers && mockHandler.headers[header] ) {233 // Return arbitrary headers234 return mockHandler.headers[header];235 } else if ( header.toLowerCase() == 'last-modified' ) {236 return mockHandler.lastModified || (new Date()).toString();237 } else if ( header.toLowerCase() == 'etag' ) {238 return mockHandler.etag || '';239 } else if ( header.toLowerCase() == 'content-type' ) {240 return mockHandler.contentType || 'text/plain';241 }242 },243 getAllResponseHeaders: function() {244 var headers = '';245 $.each(mockHandler.headers, function(k, v) {246 headers += k + ': ' + v + "\n";247 });248 return headers;249 }250 };251 }252 // Process a JSONP mock request.253 function processJsonpMock( requestSettings, mockHandler, origSettings ) {254 // Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here255 // because there isn't an easy hook for the cross domain script tag of jsonp256 processJsonpUrl( requestSettings );257 requestSettings.dataType = "json";258 if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {259 createJsonpCallback(requestSettings, mockHandler, origSettings);260 // We need to make sure261 // that a JSONP style response is executed properly262 var rurl = /^(\w+:)?\/\/([^\/?#]+)/,263 parts = rurl.exec( requestSettings.url ),264 remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);265 requestSettings.dataType = "script";266 if(requestSettings.type.toUpperCase() === "GET" && remote ) {267 var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings );268 // Check if we are supposed to return a Deferred back to the mock call, or just269 // signal success270 if(newMockReturn) {271 return newMockReturn;272 } else {273 return true;274 }275 }276 }277 return null;278 }279 // Append the required callback parameter to the end of the request URL, for a JSONP request280 function processJsonpUrl( requestSettings ) {281 if ( requestSettings.type.toUpperCase() === "GET" ) {282 if ( !CALLBACK_REGEX.test( requestSettings.url ) ) {283 requestSettings.url += (/\?/.test( requestSettings.url ) ? "&" : "?") +284 (requestSettings.jsonp || "callback") + "=?";285 }286 } else if ( !requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data) ) {287 requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?";288 }289 }290 // Process a JSONP request by evaluating the mocked response text291 function processJsonpRequest( requestSettings, mockHandler, origSettings ) {292 // Synthesize the mock request for adding a script tag293 var callbackContext = origSettings && origSettings.context || requestSettings,294 newMock = null;295 // If the response handler on the moock is a function, call it296 if ( mockHandler.response && $.isFunction(mockHandler.response) ) {297 mockHandler.response(origSettings);298 } else {299 // Evaluate the responseText javascript in a global context300 if( typeof mockHandler.responseText === 'object' ) {301 $.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')');302 } else {303 $.globalEval( '(' + mockHandler.responseText + ')');304 }305 }306 // Successful response307 jsonpSuccess( requestSettings, callbackContext, mockHandler );308 jsonpComplete( requestSettings, callbackContext, mockHandler );309 // If we are running under jQuery 1.5+, return a deferred object310 if($.Deferred){311 newMock = new $.Deferred();312 if(typeof mockHandler.responseText == "object"){313 newMock.resolveWith( callbackContext, [mockHandler.responseText] );314 }315 else{316 newMock.resolveWith( callbackContext, [$.parseJSON( mockHandler.responseText )] );317 }318 }319 return newMock;320 }321 // Create the required JSONP callback function for the request322 function createJsonpCallback( requestSettings, mockHandler, origSettings ) {323 var callbackContext = origSettings && origSettings.context || requestSettings;324 var jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++);325 // Replace the =? sequence both in the query string and the data326 if ( requestSettings.data ) {327 requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1");328 }329 requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1");330 // Handle JSONP-style loading331 window[ jsonp ] = window[ jsonp ] || function( tmp ) {332 data = tmp;333 jsonpSuccess( requestSettings, callbackContext, mockHandler );334 jsonpComplete( requestSettings, callbackContext, mockHandler );335 // Garbage collect336 window[ jsonp ] = undefined;337 try {338 delete window[ jsonp ];339 } catch(e) {}340 if ( head ) {341 head.removeChild( script );342 }343 };344 }345 // The JSONP request was successful346 function jsonpSuccess(requestSettings, callbackContext, mockHandler) {347 // If a local callback was specified, fire it and pass it the data348 if ( requestSettings.success ) {349 requestSettings.success.call( callbackContext, mockHandler.responseText || "", status, {} );350 }351 // Fire the global callback352 if ( requestSettings.global ) {353 trigger(requestSettings, "ajaxSuccess", [{}, requestSettings] );354 }355 }356 // The JSONP request was completed357 function jsonpComplete(requestSettings, callbackContext) {358 // Process result359 if ( requestSettings.complete ) {360 requestSettings.complete.call( callbackContext, {} , status );361 }362 // The request was completed363 if ( requestSettings.global ) {364 trigger( "ajaxComplete", [{}, requestSettings] );365 }366 // Handle the global AJAX counter367 if ( requestSettings.global && ! --$.active ) {368 $.event.trigger( "ajaxStop" );369 }370 }371 // The core $.ajax replacement.372 function handleAjax( url, origSettings ) {373 var mockRequest, requestSettings, mockHandler;374 // If url is an object, simulate pre-1.5 signature375 if ( typeof url === "object" ) {376 origSettings = url;377 url = undefined;378 } else {379 // work around to support 1.5 signature380 origSettings.url = url;381 }382 // Extend the original settings for the request383 requestSettings = $.extend(true, {}, $.ajaxSettings, origSettings);384 // Iterate over our mock handlers (in registration order) until we find385 // one that is willing to intercept the request386 for(var k = 0; k < mockHandlers.length; k++) {387 if ( !mockHandlers[k] ) {388 continue;389 }390 mockHandler = getMockForRequest( mockHandlers[k], requestSettings );391 if(!mockHandler) {392 // No valid mock found for this request393 continue;394 }395 mockedAjaxCalls.push(requestSettings);396 // If logging is enabled, log the mock to the console397 $.mockjaxSettings.log( mockHandler, requestSettings );398 if ( requestSettings.dataType === "jsonp" ) {399 if ((mockRequest = processJsonpMock( requestSettings, mockHandler, origSettings ))) {400 // This mock will handle the JSONP request401 return mockRequest;402 }403 }404 // Removed to fix #54 - keep the mocking data object intact405 //mockHandler.data = requestSettings.data;406 mockHandler.cache = requestSettings.cache;407 mockHandler.timeout = requestSettings.timeout;408 mockHandler.global = requestSettings.global;409 copyUrlParameters(mockHandler, origSettings);410 (function(mockHandler, requestSettings, origSettings, origHandler) {411 mockRequest = _ajax.call($, $.extend(true, {}, origSettings, {412 // Mock the XHR object413 xhr: function() { return xhr( mockHandler, requestSettings, origSettings, origHandler ); }414 }));415 })(mockHandler, requestSettings, origSettings, mockHandlers[k]);416 return mockRequest;417 }418 // We don't have a mock request419 if($.mockjaxSettings.throwUnmocked === true) {420 throw('AJAX not mocked: ' + origSettings.url);421 }422 else { // trigger a normal request423 return _ajax.apply($, [origSettings]);424 }425 }426 /**427 * Copies URL parameter values if they were captured by a regular expression428 * @param {Object} mockHandler429 * @param {Object} origSettings430 */431 function copyUrlParameters(mockHandler, origSettings) {432 //parameters aren't captured if the URL isn't a RegExp433 if (!(mockHandler.url instanceof RegExp)) {434 return;435 }436 //if no URL params were defined on the handler, don't attempt a capture437 if (!mockHandler.hasOwnProperty('urlParams')) {438 return;439 }440 var captures = mockHandler.url.exec(origSettings.url);441 //the whole RegExp match is always the first value in the capture results442 if (captures.length === 1) {443 return;444 }445 captures.shift();446 //use handler params as keys and capture resuts as values447 var i = 0,448 capturesLength = captures.length,449 paramsLength = mockHandler.urlParams.length,450 //in case the number of params specified is less than actual captures451 maxIterations = Math.min(capturesLength, paramsLength),452 paramValues = {};453 for (i; i < maxIterations; i++) {454 var key = mockHandler.urlParams[i];455 paramValues[key] = captures[i];456 }457 origSettings.urlParams = paramValues;458 }459 // Public460 $.extend({461 ajax: handleAjax462 });463 $.mockjaxSettings = {464 //url: null,465 //type: 'GET',466 log: function( mockHandler, requestSettings ) {467 if ( mockHandler.logging === false ||468 ( typeof mockHandler.logging === 'undefined' && $.mockjaxSettings.logging === false ) ) {469 return;470 }471 if ( window.console && console.log ) {472 var message = 'MOCK ' + requestSettings.type.toUpperCase() + ': ' + requestSettings.url;473 var request = $.extend({}, requestSettings);474 if (typeof console.log === 'function') {475 console.log(message, request);476 } else {477 try {478 console.log( message + ' ' + JSON.stringify(request) );479 } catch (e) {480 console.log(message);481 }482 }483 }484 },485 logging: true,486 status: 200,487 statusText: "OK",488 responseTime: 500,489 isTimeout: false,490 throwUnmocked: false,491 contentType: 'text/plain',492 response: '',493 responseText: '',494 responseXML: '',495 proxy: '',496 proxyType: 'GET',497 lastModified: null,498 etag: '',499 headers: {500 etag: 'IJF@H#@923uf8023hFO@I#H#',501 'content-type' : 'text/plain'502 }503 };504 $.mockjax = function(settings) {505 var i = mockHandlers.length;506 mockHandlers[i] = settings;507 return i;508 };509 $.mockjaxClear = function(i) {510 if ( arguments.length == 1 ) {511 mockHandlers[i] = null;512 } else {513 mockHandlers = [];514 }515 mockedAjaxCalls = [];516 };517 $.mockjax.handler = function(i) {518 if ( arguments.length == 1 ) {519 return mockHandlers[i];520 }521 };522 $.mockjax.mockedAjaxCalls = function() {523 return mockedAjaxCalls;524 };...
test-peripheral.js
Source:test-peripheral.js
1var should = require('should');2var sinon = require('sinon');3var Peripheral = require('../lib/peripheral');4describe('Peripheral', function() {5 var mockNoble = null;6 var mockId = 'mock-id';7 var mockAddress = 'mock-address';8 var mockAddressType = 'mock-address-type';9 var mockConnectable = 'mock-connectable';10 var mockAdvertisement = 'mock-advertisement';11 var mockRssi = 'mock-rssi';12 var mockHandle = 'mock-handle';13 var mockData = 'mock-data';14 var peripheral = null;15 beforeEach(function() {16 mockNoble = {17 connect: sinon.spy(),18 disconnect: sinon.spy(),19 updateRssi: sinon.spy(),20 discoverServices: sinon.spy(),21 readHandle: sinon.spy(),22 writeHandle: sinon.spy()23 };24 peripheral = new Peripheral(mockNoble, mockId, mockAddress, mockAddressType, mockConnectable, mockAdvertisement, mockRssi);25 });26 afterEach(function() {27 peripheral = null;28 });29 it('should have a id', function() {30 peripheral.id.should.equal(mockId);31 });32 it('should have an address', function() {33 peripheral.address.should.equal(mockAddress);34 });35 it('should have an address type', function() {36 peripheral.addressType.should.equal(mockAddressType);37 });38 it('should have connectable', function() {39 peripheral.connectable.should.equal(mockConnectable);40 });41 it('should have advertisement', function() {42 peripheral.advertisement.should.equal(mockAdvertisement);43 });44 it('should have rssi', function() {45 peripheral.rssi.should.equal(mockRssi);46 });47 describe('toString', function() {48 it('should be id, address, address type, connectable, advertisement, rssi, state', function() {49 peripheral.toString().should.equal('{"id":"mock-id","address":"mock-address","addressType":"mock-address-type","connectable":"mock-connectable","advertisement":"mock-advertisement","rssi":"mock-rssi","state":"disconnected"}');50 });51 });52 describe('connect', function() {53 it('should delegate to noble', function() {54 peripheral.connect();55 mockNoble.connect.calledWithExactly(mockId).should.equal(true);56 });57 it('should callback', function() {58 var calledback = false;59 peripheral.connect(function() {60 calledback = true;61 });62 peripheral.emit('connect');63 calledback.should.equal(true);64 });65 });66 describe('disconnect', function() {67 it('should delegate to noble', function() {68 peripheral.disconnect();69 mockNoble.disconnect.calledWithExactly(mockId).should.equal(true);70 });71 it('should callback', function() {72 var calledback = false;73 peripheral.disconnect(function() {74 calledback = true;75 });76 peripheral.emit('disconnect');77 calledback.should.equal(true);78 });79 });80 describe('updateRssi', function() {81 it('should delegate to noble', function() {82 peripheral.updateRssi();83 mockNoble.updateRssi.calledWithExactly(mockId).should.equal(true);84 });85 it('should callback', function() {86 var calledback = false;87 peripheral.updateRssi(function() {88 calledback = true;89 });90 peripheral.emit('rssiUpdate');91 calledback.should.equal(true);92 });93 it('should callback with rssi', function() {94 var calledbackRssi = null;95 peripheral.updateRssi(function(error, rssi) {96 calledbackRssi = rssi;97 });98 peripheral.emit('rssiUpdate', mockRssi);99 calledbackRssi.should.equal(mockRssi);100 });101 });102 describe('discoverServices', function() {103 it('should delegate to noble', function() {104 peripheral.discoverServices();105 mockNoble.discoverServices.calledWithExactly(mockId, undefined).should.equal(true);106 });107 it('should delegate to noble, service uuids', function() {108 var mockServiceUuids = [];109 peripheral.discoverServices(mockServiceUuids);110 mockNoble.discoverServices.calledWithExactly(mockId, mockServiceUuids).should.equal(true);111 });112 it('should callback', function() {113 var calledback = false;114 peripheral.discoverServices(null, function() {115 calledback = true;116 });117 peripheral.emit('servicesDiscover');118 calledback.should.equal(true);119 });120 it('should callback with services', function() {121 var mockServices = [];122 var calledbackServices = null;123 peripheral.discoverServices(null, function(error, services) {124 calledbackServices = services;125 });126 peripheral.emit('servicesDiscover', mockServices);127 calledbackServices.should.equal(mockServices);128 });129 });130 describe('discoverSomeServicesAndCharacteristics', function() {131 var mockServiceUuids = [];132 var mockCharacteristicUuids = [];133 var mockServices = null;134 beforeEach(function() {135 peripheral.discoverServices = sinon.spy();136 mockServices = [137 {138 uuid: '1',139 discoverCharacteristics: sinon.spy()140 },141 {142 uuid: '2',143 discoverCharacteristics: sinon.spy()144 }145 ];146 });147 it('should call discoverServices', function() {148 peripheral.discoverSomeServicesAndCharacteristics(mockServiceUuids);149 peripheral.discoverServices.calledWith(mockServiceUuids).should.equal(true);150 });151 it('should call discoverCharacteristics on each service discovered', function() {152 peripheral.discoverSomeServicesAndCharacteristics(mockServiceUuids, mockCharacteristicUuids);153 var discoverServicesCallback = peripheral.discoverServices.getCall(0).args[1];154 discoverServicesCallback(null, mockServices);155 mockServices[0].discoverCharacteristics.calledWith(mockCharacteristicUuids).should.equal(true);156 mockServices[1].discoverCharacteristics.calledWith(mockCharacteristicUuids).should.equal(true);157 });158 it('should callback', function() {159 var calledback = false;160 peripheral.discoverSomeServicesAndCharacteristics(mockServiceUuids, mockCharacteristicUuids, function() {161 calledback = true;162 });163 var discoverServicesCallback = peripheral.discoverServices.getCall(0).args[1];164 discoverServicesCallback(null, mockServices);165 mockServices[0].discoverCharacteristics.getCall(0).args[1](null, []);166 mockServices[1].discoverCharacteristics.getCall(0).args[1](null, []);167 calledback.should.equal(true);168 });169 it('should callback with the services and characteristics discovered', function() {170 var calledbackServices = null;171 var calledbackCharacteristics = null;172 peripheral.discoverSomeServicesAndCharacteristics(mockServiceUuids, mockCharacteristicUuids, function(err, services, characteristics) {173 calledbackServices = services;174 calledbackCharacteristics = characteristics;175 });176 var discoverServicesCallback = peripheral.discoverServices.getCall(0).args[1];177 discoverServicesCallback(null, mockServices);178 var mockCharacteristic1 = { uuid: '1' };179 var mockCharacteristic2 = { uuid: '2' };180 var mockCharacteristic3 = { uuid: '3' };181 mockServices[0].discoverCharacteristics.getCall(0).args[1](null, [mockCharacteristic1]);182 mockServices[1].discoverCharacteristics.getCall(0).args[1](null, [mockCharacteristic2, mockCharacteristic3]);183 calledbackServices.should.equal(mockServices);184 calledbackCharacteristics.should.eql([mockCharacteristic1, mockCharacteristic2, mockCharacteristic3]);185 });186 });187 describe('discoverAllServicesAndCharacteristics', function() {188 it('should call discoverSomeServicesAndCharacteristics', function() {189 var mockCallback = sinon.spy();190 peripheral.discoverSomeServicesAndCharacteristics = sinon.spy();191 peripheral.discoverAllServicesAndCharacteristics(mockCallback);192 peripheral.discoverSomeServicesAndCharacteristics.calledWithExactly([], [], mockCallback).should.equal(true);193 });194 });195 describe('readHandle', function() {196 it('should delegate to noble', function() {197 peripheral.readHandle(mockHandle);198 mockNoble.readHandle.calledWithExactly(mockId, mockHandle).should.equal(true);199 });200 it('should callback', function() {201 var calledback = false;202 peripheral.readHandle(mockHandle, function() {203 calledback = true;204 });205 peripheral.emit('handleRead' + mockHandle);206 calledback.should.equal(true);207 });208 it('should callback with data', function() {209 var calledbackData = null;210 peripheral.readHandle(mockHandle, function(error, data) {211 calledbackData = data;212 });213 peripheral.emit('handleRead' + mockHandle, mockData);214 calledbackData.should.equal(mockData);215 });216 });217 describe('writeHandle', function() {218 beforeEach(function() {219 mockData = new Buffer(0);220 });221 it('should only accept data as a buffer', function() {222 mockData = {};223 (function(){224 peripheral.writeHandle(mockHandle, mockData);225 }).should.throwError('data must be a Buffer');226 });227 it('should delegate to noble, withoutResponse false', function() {228 peripheral.writeHandle(mockHandle, mockData, false);229 mockNoble.writeHandle.calledWithExactly(mockId, mockHandle, mockData, false).should.equal(true);230 });231 it('should delegate to noble, withoutResponse true', function() {232 peripheral.writeHandle(mockHandle, mockData, true);233 mockNoble.writeHandle.calledWithExactly(mockId, mockHandle, mockData, true).should.equal(true);234 });235 it('should callback', function() {236 var calledback = false;237 peripheral.writeHandle(mockHandle, mockData, false, function() {238 calledback = true;239 });240 peripheral.emit('handleWrite' + mockHandle);241 calledback.should.equal(true);242 });243 });...
strictmock_test.js
Source:strictmock_test.js
1// Copyright 2008 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14goog.provide('goog.testing.StrictMockTest');15goog.setTestOnly('goog.testing.StrictMockTest');16goog.require('goog.testing.StrictMock');17goog.require('goog.testing.jsunit');18// The object that we will be mocking19var RealObject = function() {};20RealObject.prototype.a = function() {21 fail('real object should never be called');22};23RealObject.prototype.b = function() {24 fail('real object should never be called');25};26RealObject.prototype.c = function() {27 fail('real object should never be called');28};29var mock;30function setUp() {31 var obj = new RealObject();32 mock = new goog.testing.StrictMock(obj);33}34function testMockFunction() {35 var mock = new goog.testing.StrictMock(RealObject);36 mock.a();37 mock.b();38 mock.c();39 mock.$replay();40 mock.a();41 mock.b();42 mock.c();43 mock.$verify();44 mock.$reset();45 assertThrows(function() { mock.x() });46}47function testSimpleExpectations() {48 mock.a();49 mock.$replay();50 mock.a();51 mock.$verify();52 mock.$reset();53 mock.a();54 mock.b();55 mock.a();56 mock.a();57 mock.$replay();58 mock.a();59 mock.b();60 mock.a();61 mock.a();62 mock.$verify();63}64function testFailToSetExpectation() {65 mock.$replay();66 assertThrowsJsUnitException(goog.bind(mock.a, mock));67 mock.$reset();68 mock.$replay();69 assertThrowsJsUnitException(goog.bind(mock.b, mock));70}71function testUnexpectedCall() {72 mock.a();73 mock.$replay();74 mock.a();75 assertThrowsJsUnitException(goog.bind(mock.a, mock));76 mock.$reset();77 mock.a();78 mock.$replay();79 assertThrowsJsUnitException(goog.bind(mock.b, mock));80}81function testNotEnoughCalls() {82 mock.a();83 mock.$replay();84 assertThrowsJsUnitException(goog.bind(mock.$verify, mock));85 mock.$reset();86 mock.a();87 mock.b();88 mock.$replay();89 mock.a();90 assertThrowsJsUnitException(goog.bind(mock.$verify, mock));91}92function testOutOfOrderCalls() {93 mock.a();94 mock.b();95 mock.$replay();96 assertThrowsJsUnitException(goog.bind(mock.b, mock));97}98function testVerify() {99 mock.a();100 mock.$replay();101 mock.a();102 mock.$verify();103 mock.$reset();104 mock.a();105 mock.$replay();106 assertThrowsJsUnitException(goog.bind(mock.$verify, mock));107}108function testArgumentMatching() {109 mock.a('foo');110 mock.b('bar');111 mock.$replay();112 mock.a('foo');113 assertThrowsJsUnitException(function() { mock.b('foo') });114 mock.$reset();115 mock.a('foo');116 mock.a('bar');117 mock.$replay();118 mock.a('foo');119 mock.a('bar');120 mock.$verify();121 mock.$reset();122 mock.a('foo');123 mock.a('bar');124 mock.$replay();125 assertThrowsJsUnitException(function() { mock.a('bar') });126}127function testReturnValue() {128 mock.a().$returns(5);129 mock.$replay();130 assertEquals('Mock should return the right value', 5, mock.a());131 mock.$verify();132}133function testMultipleReturnValues() {134 mock.a().$returns(3);135 mock.a().$returns(2);136 mock.a().$returns(1);137 mock.$replay();138 assertArrayEquals(139 'Mock should return the right value sequence', [3, 2, 1],140 [mock.a(), mock.a(), mock.a()]);141 mock.$verify();142}143function testAtMostOnce() {144 // Zero times SUCCESS.145 mock.a().$atMostOnce();146 mock.$replay();147 mock.$verify();148 mock.$reset();149 // One time SUCCESS.150 mock.a().$atMostOnce();151 mock.$replay();152 mock.a();153 mock.$verify();154 mock.$reset();155 // Many times FAIL.156 mock.a().$atMostOnce();157 mock.$replay();158 mock.a();159 assertThrowsJsUnitException(goog.bind(mock.a, mock));160 mock.$reset();161 // atMostOnce only lasts until a new method is called.162 mock.a().$atMostOnce();163 mock.b();164 mock.a();165 mock.$replay();166 mock.b();167 assertThrowsJsUnitException(goog.bind(mock.$verify, mock));168}169function testAtLeastOnce() {170 // atLeastOnce does not mean zero times171 mock.a().$atLeastOnce();172 mock.$replay();173 assertThrowsJsUnitException(goog.bind(mock.$verify, mock));174 mock.$reset();175 // atLeastOnce does mean three times176 mock.a().$atLeastOnce();177 mock.$replay();178 mock.a();179 mock.a();180 mock.a();181 mock.$verify();182 mock.$reset();183 // atLeastOnce only lasts until a new method is called184 mock.a().$atLeastOnce();185 mock.b();186 mock.a();187 mock.$replay();188 mock.a();189 mock.a();190 mock.b();191 mock.a();192 assertThrowsJsUnitException(goog.bind(mock.a, mock));193}194function testAtLeastOnceWithArgs() {195 mock.a('asdf').$atLeastOnce();196 mock.a('qwert');197 mock.$replay();198 mock.a('asdf');199 mock.a('asdf');200 mock.a('qwert');201 mock.$verify();202 mock.$reset();203 mock.a('asdf').$atLeastOnce();204 mock.a('qwert');205 mock.$replay();206 mock.a('asdf');207 mock.a('asdf');208 assertThrowsJsUnitException(function() { mock.a('zxcv') });209 assertThrowsJsUnitException(goog.bind(mock.$verify, mock));210}211function testAnyTimes() {212 mock.a().$anyTimes();213 mock.$replay();214 mock.$verify();215 mock.$reset();216 mock.a().$anyTimes();217 mock.$replay();218 mock.a();219 mock.a();220 mock.a();221 mock.a();222 mock.a();223 mock.$verify();224}225function testAnyTimesWithArguments() {226 mock.a('foo').$anyTimes();227 mock.$replay();228 mock.$verify();229 mock.$reset();230 mock.a('foo').$anyTimes();231 mock.a('bar').$anyTimes();232 mock.$replay();233 mock.a('foo');234 mock.a('foo');235 mock.a('foo');236 mock.a('bar');237 mock.a('bar');238 mock.$verify();239}240function testZeroTimes() {241 mock.a().$times(0);242 mock.$replay();243 mock.$verify();244 mock.$reset();245 mock.a().$times(0);246 mock.$replay();247 assertThrowsJsUnitException(function() { mock.a() });248}249function testZeroTimesWithArguments() {250 mock.a('foo').$times(0);251 mock.$replay();252 mock.$verify();253 mock.$reset();254 mock.a('foo').$times(0);255 mock.$replay();256 assertThrowsJsUnitException(function() { mock.a('foo') });257}258function testTooManyCalls() {259 mock.a().$times(2);260 mock.$replay();261 mock.a();262 mock.a();263 assertThrowsJsUnitException(function() { mock.a() });264}265function testTooManyCallsWithArguments() {266 mock.a('foo').$times(2);267 mock.$replay();268 mock.a('foo');269 mock.a('foo');270 assertThrowsJsUnitException(function() { mock.a('foo') });271}272function testMultipleSkippedAnyTimes() {273 mock.a().$anyTimes();274 mock.b().$anyTimes();275 mock.c().$anyTimes();276 mock.$replay();277 mock.c();278 mock.$verify();279}280function testMultipleSkippedAnyTimesWithArguments() {281 mock.a('foo').$anyTimes();282 mock.a('bar').$anyTimes();283 mock.a('baz').$anyTimes();284 mock.$replay();285 mock.a('baz');286 mock.$verify();287}288function testVerifyThrows() {289 mock.a(1);290 mock.$replay();291 mock.a(1);292 try {293 mock.a(2);294 fail('bad mock, should fail');295 } catch (ex) {296 // this could be an event handler, for example297 }298 assertThrowsJsUnitException(goog.bind(mock.$verify, mock));299}300function testThrows() {301 mock.a().$throws('exception!');302 mock.$replay();303 assertThrows(goog.bind(mock.a, mock));304 mock.$verify();305}306function testDoes() {307 mock.a(1, 2).$does(function(a, b) { return a + b; });308 mock.$replay();309 assertEquals('Mock should call the function', 3, mock.a(1, 2));310 mock.$verify();311}312function testErrorMessageForBadArgs() {313 mock.a();314 mock.$anyTimes();315 mock.$replay();316 var message;317 try {318 mock.a('a');319 } catch (e) {320 message = e.message;321 }322 assertTrue('No exception thrown on verify', goog.isDef(message));323 assertContains('Bad arguments to a()', message);...
test-characteristic.js
Source:test-characteristic.js
1var should = require('should');2var sinon = require('sinon');3var Characteristic = require('../lib/characteristic');4describe('Characteristic', function() {5 var mockNoble = null;6 var mockPeripheralId = 'mock-peripheral-id';7 var mockServiceUuid = 'mock-service-uuid';8 var mockUuid = 'mock-uuid';9 var mockProperties = ['mock-property-1', 'mock-property-2'];10 var characteristic = null;11 beforeEach(function() {12 mockNoble = {13 read: sinon.spy(),14 write: sinon.spy(),15 broadcast: sinon.spy(),16 notify: sinon.spy(),17 discoverDescriptors: sinon.spy()18 };19 characteristic = new Characteristic(mockNoble, mockPeripheralId, mockServiceUuid, mockUuid, mockProperties);20 });21 afterEach(function() {22 characteristic = null;23 });24 it('should have a uuid', function() {25 characteristic.uuid.should.equal(mockUuid);26 });27 it('should lookup name and type by uuid', function() {28 characteristic = new Characteristic(mockNoble, mockPeripheralId, mockServiceUuid, '2a00', mockProperties);29 characteristic.name.should.equal('Device Name');30 characteristic.type.should.equal('org.bluetooth.characteristic.gap.device_name');31 });32 it('should have properties', function() {33 characteristic.properties.should.equal(mockProperties);34 });35 describe('toString', function() {36 it('should be uuid, name, type, properties', function() {37 characteristic.toString().should.equal('{"uuid":"mock-uuid","name":null,"type":null,"properties":["mock-property-1","mock-property-2"]}');38 });39 });40 describe('read', function() {41 it('should delegate to noble', function() {42 characteristic.read();43 mockNoble.read.calledWithExactly(mockPeripheralId, mockServiceUuid, mockUuid).should.equal(true);44 });45 it('should callback', function() {46 var calledback = false;47 characteristic.read(function() {48 calledback = true;49 });50 characteristic.emit('read');51 calledback.should.equal(true);52 });53 it('should callback with data', function() {54 var mockData = new Buffer(0);55 var callbackData = null;56 characteristic.read(function(error, data) {57 callbackData = data;58 });59 characteristic.emit('read', mockData);60 callbackData.should.equal(mockData);61 });62 });63 describe('write', function() {64 var mockData = null;65 beforeEach(function() {66 mockData = new Buffer(0);67 });68 it('should only accept data as a buffer', function() {69 mockData = {};70 (function(){71 characteristic.write(mockData);72 }).should.throwError('data must be a Buffer');73 });74 it('should delegate to noble, withoutResponse false', function() {75 characteristic.write(mockData, false);76 mockNoble.write.calledWithExactly(mockPeripheralId, mockServiceUuid, mockUuid, mockData, false).should.equal(true);77 });78 it('should delegate to noble, withoutResponse true', function() {79 characteristic.write(mockData, true);80 mockNoble.write.calledWithExactly(mockPeripheralId, mockServiceUuid, mockUuid, mockData, true).should.equal(true);81 });82 it('should callback', function() {83 var calledback = false;84 characteristic.write(mockData, true, function() {85 calledback = true;86 });87 characteristic.emit('write');88 calledback.should.equal(true);89 });90 });91 describe('broadcast', function() {92 it('should delegate to noble, true', function() {93 characteristic.broadcast(true);94 mockNoble.broadcast.calledWithExactly(mockPeripheralId, mockServiceUuid, mockUuid, true).should.equal(true);95 });96 it('should delegate to noble, false', function() {97 characteristic.broadcast(false);98 mockNoble.broadcast.calledWithExactly(mockPeripheralId, mockServiceUuid, mockUuid, false).should.equal(true);99 });100 it('should callback', function() {101 var calledback = false;102 characteristic.broadcast(true, function() {103 calledback = true;104 });105 characteristic.emit('broadcast');106 calledback.should.equal(true);107 });108 });109 describe('notify', function() {110 it('should delegate to noble, true', function() {111 characteristic.notify(true);112 mockNoble.notify.calledWithExactly(mockPeripheralId, mockServiceUuid, mockUuid, true).should.equal(true);113 });114 it('should delegate to noble, false', function() {115 characteristic.notify(false);116 mockNoble.notify.calledWithExactly(mockPeripheralId, mockServiceUuid, mockUuid, false).should.equal(true);117 });118 it('should callback', function() {119 var calledback = false;120 characteristic.notify(true, function() {121 calledback = true;122 });123 characteristic.emit('notify');124 calledback.should.equal(true);125 });126 });127 describe('subscribe', function() {128 it('should delegate to noble notify, true', function() {129 characteristic.subscribe();130 mockNoble.notify.calledWithExactly(mockPeripheralId, mockServiceUuid, mockUuid, true).should.equal(true);131 });132 it('should callback', function() {133 var calledback = false;134 characteristic.subscribe(function() {135 calledback = true;136 });137 characteristic.emit('notify');138 calledback.should.equal(true);139 });140 });141 describe('unsubscribe', function() {142 it('should delegate to noble notify, false', function() {143 characteristic.unsubscribe();144 mockNoble.notify.calledWithExactly(mockPeripheralId, mockServiceUuid, mockUuid, false).should.equal(true);145 });146 it('should callback', function() {147 var calledback = false;148 characteristic.unsubscribe(function() {149 calledback = true;150 });151 characteristic.emit('notify');152 calledback.should.equal(true);153 });154 });155 describe('discoverDescriptors', function() {156 it('should delegate to noble', function() {157 characteristic.discoverDescriptors();158 mockNoble.discoverDescriptors.calledWithExactly(mockPeripheralId, mockServiceUuid, mockUuid).should.equal(true);159 });160 it('should callback', function() {161 var calledback = false;162 characteristic.discoverDescriptors(function() {163 calledback = true;164 });165 characteristic.emit('descriptorsDiscover');166 calledback.should.equal(true);167 });168 it('should callback with descriptors', function() {169 var mockDescriptors = [];170 var callbackDescriptors = null;171 characteristic.discoverDescriptors(function(error, descriptors) {172 callbackDescriptors = descriptors;173 });174 characteristic.emit('descriptorsDiscover', mockDescriptors);175 callbackDescriptors.should.equal(mockDescriptors);176 });177 });...
mockcontrol.js
Source:mockcontrol.js
1// Copyright 2008 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7// http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.14/**15 * @fileoverview A MockControl holds a set of mocks for a particular test.16 * It consolidates calls to $replay, $verify, and $tearDown, which simplifies17 * the test and helps avoid omissions.18 *19 * You can create and control a mock:20 * var mockFoo = mockControl.addMock(new MyMock(Foo));21 *22 * MockControl also exposes some convenience functions that create23 * controlled mocks for common mocks: StrictMock, LooseMock,24 * FunctionMock, MethodMock, and GlobalFunctionMock.25 *26 */27goog.provide('goog.testing.MockControl');28goog.require('goog.array');29goog.require('goog.testing');30goog.require('goog.testing.LooseMock');31goog.require('goog.testing.MockInterface');32goog.require('goog.testing.StrictMock');33/**34 * Controls a set of mocks. Controlled mocks are replayed, verified, and35 * cleaned-up at the same time.36 * @constructor37 */38goog.testing.MockControl = function() {39 /**40 * The list of mocks being controlled.41 * @type {Array.<goog.testing.MockInterface>}42 * @private43 */44 this.mocks_ = [];45};46/**47 * Takes control of this mock.48 * @param {goog.testing.MockInterface} mock Mock to be controlled.49 * @return {goog.testing.MockInterface} The same mock passed in,50 * for convenience.51 */52goog.testing.MockControl.prototype.addMock = function(mock) {53 this.mocks_.push(mock);54 return mock;55};56/**57 * Calls replay on each controlled mock.58 */59goog.testing.MockControl.prototype.$replayAll = function() {60 goog.array.forEach(this.mocks_, function(m) {61 m.$replay();62 });63};64/**65 * Calls reset on each controlled mock.66 */67goog.testing.MockControl.prototype.$resetAll = function() {68 goog.array.forEach(this.mocks_, function(m) {69 m.$reset();70 });71};72/**73 * Calls verify on each controlled mock.74 */75goog.testing.MockControl.prototype.$verifyAll = function() {76 goog.array.forEach(this.mocks_, function(m) {77 m.$verify();78 });79};80/**81 * Calls tearDown on each controlled mock, if necesssary.82 */83goog.testing.MockControl.prototype.$tearDown = function() {84 goog.array.forEach(this.mocks_, function(m) {85 // $tearDown if defined.86 if (m.$tearDown) {87 m.$tearDown();88 }89 // TODO(user): Somehow determine if verifyAll should have been called90 // but was not.91 });92};93/**94 * Creates a controlled StrictMock. Passes its arguments through to the95 * StrictMock constructor.96 * @param {Object} objectToMock The object to mock.97 * @param {boolean=} opt_mockStaticMethods An optional argument denoting that98 * a mock should be constructed from the static functions of a class.99 * @param {boolean=} opt_createProxy An optional argument denoting that100 * a proxy for the target mock should be created.101 * @return {goog.testing.StrictMock} The mock object.102 */103goog.testing.MockControl.prototype.createStrictMock = function(104 objectToMock, opt_mockStaticMethods, opt_createProxy) {105 var m = new goog.testing.StrictMock(objectToMock, opt_mockStaticMethods,106 opt_createProxy);107 this.addMock(m);108 return m;109};110/**111 * Creates a controlled LooseMock. Passes its arguments through to the112 * LooseMock constructor.113 * @param {Object} objectToMock The object to mock.114 * @param {boolean=} opt_ignoreUnexpectedCalls Whether to ignore unexpected115 * calls.116 * @param {boolean=} opt_mockStaticMethods An optional argument denoting that117 * a mock should be constructed from the static functions of a class.118 * @param {boolean=} opt_createProxy An optional argument denoting that119 * a proxy for the target mock should be created.120 * @return {goog.testing.LooseMock} The mock object.121 */122goog.testing.MockControl.prototype.createLooseMock = function(123 objectToMock, opt_ignoreUnexpectedCalls,124 opt_mockStaticMethods, opt_createProxy) {125 var m = new goog.testing.LooseMock(objectToMock, opt_ignoreUnexpectedCalls,126 opt_mockStaticMethods, opt_createProxy);127 this.addMock(m);128 return m;129};130/**131 * Creates a controlled FunctionMock. Passes its arguments through to the132 * FunctionMock constructor.133 * @param {string=} opt_functionName The optional name of the function to mock134 * set to '[anonymous mocked function]' if not passed in.135 * @return {goog.testing.MockInterface} The mocked function.136 */137goog.testing.MockControl.prototype.createFunctionMock = function(138 opt_functionName) {139 var m = goog.testing.createFunctionMock(opt_functionName);140 this.addMock(m);141 return m;142};143/**144 * Creates a controlled MethodMock. Passes its arguments through to the145 * MethodMock constructor.146 * @param {Object} scope The scope of the method to be mocked out.147 * @param {string} functionName The name of the function we're going to mock.148 * @return {goog.testing.MockInterface} The mocked method.149 */150goog.testing.MockControl.prototype.createMethodMock = function(151 scope, functionName) {152 var m = goog.testing.createMethodMock(scope, functionName);153 this.addMock(m);154 return m;155};156/**157 * Creates a controlled MethodMock for a constructor. Passes its arguments158 * through to the MethodMock constructor. See159 * {@link goog.testing.createConstructorMock} for details.160 * @param {Object} scope The scope of the constructor to be mocked out.161 * @param {string} constructorName The name of the function we're going to mock.162 * @return {goog.testing.MockInterface} The mocked method.163 */164goog.testing.MockControl.prototype.createConstructorMock = function(165 scope, constructorName) {166 var m = goog.testing.createConstructorMock(scope, constructorName);167 this.addMock(m);168 return m;169};170/**171 * Creates a controlled GlobalFunctionMock. Passes its arguments through to the172 * GlobalFunctionMock constructor.173 * @param {string} functionName The name of the function we're going to mock.174 * @return {goog.testing.MockInterface} The mocked function.175 */176goog.testing.MockControl.prototype.createGlobalFunctionMock = function(177 functionName) {178 var m = goog.testing.createGlobalFunctionMock(functionName);179 this.addMock(m);180 return m;...
index.js
Source:index.js
...11import fileResource from "./fileResource";12import adSite from "./adSite";13import ad from "./ad";14// ç»å½ç¸å
³15Mock.mock(/\/admin\/auth\/login\/out/, "post", login.out);16Mock.mock(/\/admin\/auth\/login\/password/, "post", login.password);17Mock.mock(/\/admin\/auth\/login\/index/, "post", login.index);18Mock.mock(/\/admin\/auth\/login\/userInfo/, "get", login.userInfo);19// 管çåç¸å
³20Mock.mock(/\/admin\/auth\/admin\/index/, "get", authAdmin.index);21Mock.mock(/\/admin\/auth\/admin\/roleList/, "get", authAdmin.roleList);22Mock.mock(/\/admin\/auth\/admin\/save/, "post", authAdmin.save);23Mock.mock(/\/admin\/auth\/admin\/edit/, "post", authAdmin.edit);24Mock.mock(/\/admin\/auth\/admin\/delete/, "post", authAdmin.del);25// æéç¸å
³26Mock.mock(27 /\/admin\/auth\/permission_rule\/index/,28 "get",29 authPermissionRule.index30);31Mock.mock(32 /\/admin\/auth\/permission_rule\/save/,33 "post",34 authPermissionRule.save35);36Mock.mock(37 /\/admin\/auth\/permission_rule\/edit/,38 "post",39 authPermissionRule.edit40);41Mock.mock(42 /\/admin\/auth\/permission_rule\/delete/,43 "post",44 authPermissionRule.del45);46// è§è²ç¸å
³47Mock.mock(/\/admin\/auth\/role\/index/, "get", authRole.index);48Mock.mock(/\/admin\/auth\/role\/save/, "post", authRole.save);49Mock.mock(/\/admin\/auth\/role\/edit/, "post", authRole.edit);50Mock.mock(/\/admin\/auth\/role\/delete/, "post", authRole.del);51Mock.mock(/\/admin\/auth\/role\/authList/, "get", authRole.authList);52Mock.mock(/\/admin\/auth\/role\/auth/, "post", authRole.auth);53/**54 * ä¸ä¼ ç¸å
³55 */56// è·åæ件å表57Mock.mock(/admin\/file\/upload\/qiuNiuUpToken/, "get", upload.qiuNiuUpToken);58// ä¸ä¼ æ件59Mock.mock(/admin\/file\/upload\/createFile/, "post", upload.createFile);60/**61 * èµæºåç»ç¸å
³62 */63// è·åèµæºåç»å表64Mock.mock(/admin\/file\/resource_tag\/index/, "get", fileResourceTag.index);65// æ°å»ºèµæºåç»66Mock.mock(/admin\/file\/resource_tag\/add/, "post", fileResourceTag.add);67/**68 * èµæºç¸å
³69 */70// è·åèµæºå表71Mock.mock(/admin\/file\/resource\/index/, "get", fileResource.index);72// ä¸ä¼ èµæº73Mock.mock(/admin\/file\/resource\/add/, "post", fileResource.add);74// 广åä½ç¸å
³75Mock.mock(/\/admin\/ad\/site\/index/, "get", adSite.index);76Mock.mock(/\/admin\/ad\/site\/adList/, "post", adSite.adList);77Mock.mock(/\/admin\/ad\/site\/save/, "post", adSite.save);78Mock.mock(/\/admin\/ad\/site\/edit/, "post", adSite.edit);79Mock.mock(/\/admin\/ad\/site\/delete/, "post", adSite.del);80// 广åç¸å
³81Mock.mock(/\/admin\/ad\/ad\/index/, "get", ad.index);82Mock.mock(/\/admin\/ad\/ad\/save/, "post", ad.save);83Mock.mock(/\/admin\/ad\/ad\/edit/, "post", ad.edit);84Mock.mock(/\/admin\/ad\/ad\/delete/, "post", ad.del);...
Using AI Code Generation
1var webdriverio = require('webdriverio');2var mock = require('mock-require');3mock('webdriverio', webdriverio);4var request = require('request');5mock('request', request);6var expect = require('chai').expect;7var assert = require('chai').assert;8var should = require('chai').should();9var webdriverio = require('webdriverio');10var options = { desiredCapabilities: { browserName: 'chrome' } };11var client = webdriverio.remote(options);12describe('Test', function () {13 it('should work', function () {14 .setValue('#lst-ib', 'webdriverio')15 .click('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)')16 .getTitle().then(function (title) {17 console.log('Title was: ' + title);18 })19 .end();20 });21});22var webdriverio = require('webdriverio');23var mock = require('mock-require');24mock('webdriverio', webdriverio);25var expect = require('chai').expect;26var assert = require('chai').assert;27var should = require('chai').should();28var webdriverio = require('webdriverio');29var options = { desiredCapabilities: { browserName: 'chrome' } };30var client = webdriverio.remote(options);31describe('Test', function () {32 it('should work', function () {33 .setValue('#lst-ib', 'webdriverio')34 .click('#tsf > div.tsf-p > div.jsb > center > input[type="submit"]:nth-child(1)')35 .getTitle().then(function (title) {36 console.log('Title was: ' + title);37 })38 .end();39 });40});
Using AI Code Generation
1const mock = require('mock-require');2mock('webdriverio', require('webdriverio-mock'));3const mock = require('mock-require');4mock('webdriverio', require('webdriverio-mock'));5const mock = require('mock-require');6mock('webdriverio', require('webdriverio-mock'));7const mock = require('mock-require');8mock('webdriverio', require('webdriverio-mock'));9const mock = require('mock-require');10mock('webdriverio', require('webdriverio-mock'));11const mock = require('mock-require');12mock('webdriverio', require('webdriverio-mock'));13const mock = require('mock-require');14mock('webdriverio', require('webdriverio-mock'));15const mock = require('mock-require');16mock('webdriverio', require('webdriverio-mock'));17const mock = require('mock-require');18mock('webdriverio', require('webdriverio-mock'));19const mock = require('mock-require');20mock('webdriverio', require('webdriverio-mock'));21const mock = require('mock-require');22mock('webdriverio', require('webdriverio-mock'));23const mock = require('mock-require');24mock('webdriverio', require('webdriverio-mock'));25const mock = require('mock-require');26mock('webdriverio', require('webdriverio-mock'));27const mock = require('mock-require');
Using AI Code Generation
1var webdriverio = require('webdriverio');2var mock = require('mock-require');3mock('webdriverio', webdriverio);4var webdriverio = require('webdriverio');5var mock = require('mock-require');6mock('webdriverio', webdriverio);7var webdriverio = require('webdriverio');8var mock = require('mock-require');9mock('webdriverio', webdriverio);10var webdriverio = require('webdriverio');11var mock = require('mock-require');12mock('webdriverio', webdriverio);13var webdriverio = require('webdriverio');14var mock = require('mock-require');15mock('webdriverio', webdriverio);16var webdriverio = require('webdriverio');17var mock = require('mock-require');18mock('webdriverio', webdriverio);19var webdriverio = require('webdriverio');20var mock = require('mock-require');21mock('webdriverio', webdriverio);22var webdriverio = require('webdriverio');23var mock = require('mock-require');24mock('webdriverio', webdriverio);25var webdriverio = require('webdriverio');26var mock = require('mock-require');27mock('webdriverio', webdriverio);28var webdriverio = require('webdriverio');29var mock = require('mock-require');30mock('webdriverio', webdriverio);31var webdriverio = require('webdriverio');32var mock = require('mock-require');
Using AI Code Generation
1const mock = require('mock-require');2const { remote } = require('webdriverio');3mock('webdriverio', {4 remote: jest.fn().mockImplementation(() => {5 return {6 click: jest.fn().mockResolvedValue(),7 setValue: jest.fn().mockResolvedValue(),8 getTitle: jest.fn().mockResolvedValue('Google')9 }10 })11});12describe('Google', () => {13 it('should be titled "Google"', async () => {14 const browser = await remote({15 capabilities: {16 }17 });18 await browser.click('input[name="q"]');19 await browser.setValue('input[name="q"]', 'webdriverio');20 await browser.keys('Enter');21 const title = await browser.getTitle();22 expect(title).toBe('Google');23 await browser.deleteSession();24 });25});26 at Object.remote (node_modules/webdriverio/build/index.js:21:19)27 at Object.<anonymous> (test.js:24:24)28 at step (test.js:32:23)29 at Object.next (test.js:13:53)30 at fulfilled (test.js:4:58)31 at processTicksAndRejections (internal/process/task_queues.js:97:5)
Using AI Code Generation
1const webdriverio = require('webdriverio');2const mock = require('mock-require');3mock('webdriverio', webdriverio);4const webdriverio = require('webdriverio');5const mock = require('mock-require');6mock('webdriverio', webdriverio);
Using AI Code Generation
1const mock = require('mock-require');2mock('webdriverio', {3 remote: () => ({4 $: () => ({5 getText: () => new Promise(resolve => resolve('mocked text')),6 setValue: () => new Promise(resolve => resolve('mocked text')),7 isExisting: () => new Promise(resolve => resolve(true)),8 click: () => new Promise(resolve => resolve('mocked text')),9 waitForExist: () => new Promise(resolve => resolve('mocked text')),10 waitForVisible: () => new Promise(resolve => resolve('mocked text')),11 waitForEnabled: () => new Promise(resolve => resolve('mocked text')),12 waitForText: () => new Promise(resolve => resolve('mocked text')),13 getAttribute: () => new Promise(resolve => resolve('mocked text')),14 getHTML: () => new Promise(resolve => resolve('mocked text')),15 getValue: () => new Promise(resolve => resolve('mocked text')),16 selectByVisibleText: () => new Promise(resolve => resolve('mocked text')),17 selectByAttribute: () => new Promise(resolve => resolve('mocked text')),18 selectByIndex: () => new Promise(resolve => resolve('mocked text')),19 selectByValue: () => new Promise(resolve => resolve('mocked text')),20 addValue: () => new Promise(resolve => resolve('mocked text')),21 clearElement: () => new Promise(resolve => resolve('mocked text')),22 dragAndDrop: () => new Promise(resolve => resolve('mocked text')),23 dragAndDropToObject: () => new Promise(resolve => resolve('mocked text')),24 moveTo: () => new Promise(resolve => resolve('mocked text')),25 saveScreenshot: () => new Promise(resolve => resolve('mocked text')),26 scroll: () => new Promise(resolve => resolve('mocked text')),27 scrollIntoView: () => new Promise(resolve => resolve('mocked text')),28 getTagName: () => new Promise(resolve => resolve('mocked text')),29 isDisplayed: () => new Promise(resolve => resolve('mocked text')),30 isEnabled: () => new Promise(resolve => resolve('mocked text')),31 isSelected: () => new Promise(resolve => resolve('mocked text')),32 getCSSProperty: () => new Promise(resolve => resolve('mocked text')),33 getComputedRole: () => new Promise(resolve => resolve('mocked text
Using AI Code Generation
1const mock = require('mock-require');2mock('webdriverio', {remote: () => {return {}}});3const {webdriverio} = require('webdriverio');4const mock = require('mock-require');5mock('webdriverio', {remote: () => {return {}}});6const {webdriverio} = require('webdriverio');7const mock = require('mock-require');8mock('webdriverio', {remote: () => {return {}}});9const {webdriverio} = require('webdriverio');
Using AI Code Generation
1const webdriverio = require('webdriverio');2const mock = require('mock-require');3mock('webdriverio', webdriverio);4const webdriverio = require('webdriverio');5const mock = require('mock-require');6mock('webdriverio', webdriverio);
Using AI Code Generation
1const mock = require('mock-require');2mock('webdriverio', {remote: () => {return {}}});3const {webdriverio} = require('webdriverio');4const mock = require('mock-require');5mock('webdriverio', {remote: () => {return {}}});6const {webdriverio} = require('webdriverio');7const mock = require('mock-require');8mock('webdriverio', {remote: () => {return {}}});9const {webdriverio} = require('webdriverio');
Using AI Code Generation
1import {mock} from 'webdriverio';2mock('url', { method: 'POST', response: { data: 'test' } })3mock('url', { method: 'POST', response: { data: 'test' } })4import {mock} from 'webdriverio';5mock('url', { method: 'POST', response: { data: 'test' } })6mock('url', { method: 'POST', response: { data: 'test' } })7import {mock} from 'webdriverio';8mock('url', { method: 'POST', response: { data: 'test' } })9mock('url', { method: 'POST', response: { data: 'test' } })10import {mock} from 'webdriverio';11mock('url', { method: 'POST', response: { data: 'test' } })12mock('url', { method: 'POST', response: { data: 'test' } })13import {mock} from 'webdriverio';14mock('url', { method: 'POST', response: { data: 'test' } })15mock('url', { method: 'POST', response: { data: 'test' } })16import {mock} from 'webdriverio';
Wondering what could be a next-gen browser and mobile test automation framework that is also simple and concise? Yes, that’s right, it's WebdriverIO. Since the setup is very easy to follow compared to Selenium testing configuration, you can configure the features manually thereby being the center of attraction for automation testing. Therefore the testers adopt WedriverIO to fulfill their needs of browser testing.
Learn to run automation testing with WebdriverIO tutorial. Go from a beginner to a professional automation test expert with LambdaTest WebdriverIO tutorial.
Running Your First Automation Script - Learn the steps involved to execute your first Test Automation Script using WebdriverIO since the setup is very easy to follow and the features can be configured manually.
Selenium Automation With WebdriverIO - Read more about automation testing with WebdriverIO and how it supports both browsers and mobile devices.
Browser Commands For Selenium Testing - Understand more about the barriers faced while working on your Selenium Automation Scripts in WebdriverIO, the ‘browser’ object and how to use them?
Handling Alerts & Overlay In Selenium - Learn different types of alerts faced during automation, how to handle these alerts and pops and also overlay modal in WebdriverIO.
How To Use Selenium Locators? - Understand how Webdriver uses selenium locators in a most unique way since having to choose web elements very carefully for script execution is very important to get stable test results.
Deep Selectors In Selenium WebdriverIO - The most popular automation testing framework that is extensively adopted by all the testers at a global level is WebdriverIO. Learn how you can use Deep Selectors in Selenium WebdriverIO.
Handling Dropdown In Selenium - Learn more about handling dropdowns and how it's important while performing automated browser testing.
Automated Monkey Testing with Selenium & WebdriverIO - Understand how you can leverage the amazing quality of WebdriverIO along with selenium framework to automate monkey testing of your website or web applications.
JavaScript Testing with Selenium and WebdriverIO - Speed up your Javascript testing with Selenium and WebdriverIO.
Cross Browser Testing With WebdriverIO - Learn more with this step-by-step tutorial about WebdriverIO framework and how cross-browser testing is done with WebdriverIO.
Get 100 minutes of automation test minutes FREE!!