How to use createExpect method in Playwright Internal

Best JavaScript code snippet using playwright-internal

test_api.js

Source:test_api.js Github

copy

Full Screen

...385 if (!testIsDone) {386 testIsDone = true;387 if (currentTestCase) {388 var ok = true;389 ok = createExpect(currentTestCase.tearDown.bind(currentTestCase))390 .call(null) &&391 ok;392 if (!ok && result) {393 result = [false, errorsToMessage(errors, result[1])];394 }395 currentTestCase = null;396 }397 if (!result) {398 result = testResult();399 }400 const [success, errorMessage] = /** @type {!Array} */ (result);401 if (hasWindow && window.reportMojoWebUITestResult) {402 // For "mojo_webui" test types, reportMojoWebUITestResult should already403 // be defined globally, because such tests must manually import the404 // mojo_webui_test_support.js module which defines it.405 if (success) {406 window.reportMojoWebUITestResult();407 } else {408 window.reportMojoWebUITestResult(errorMessage);409 }410 } else if (hasWindow && window.webUiTest) {411 let testRunner;412 if (webUiTest.mojom.TestRunnerPtr) {413 // For mojo WebUI tests.414 testRunner = new webUiTest.mojom.TestRunnerPtr();415 /**416 * @suppress {missingProperties} for mojo.makeRequest - internal method417 * declared in mojo/public/js/bindings.js.418 */419 const mojoMakeRequest = () => mojo.makeRequest(testRunner);420 Mojo.bindInterface(421 webUiTest.mojom.TestRunner.name, mojoMakeRequest().handle);422 } else if (webUiTest.mojom.TestRunnerRemote) {423 // For mojo-lite WebUI tests.424 testRunner = webUiTest.mojom.TestRunner.getRemote();425 } else {426 assertNotReached(427 'Mojo bindings found, but no valid test interface loaded');428 }429 if (success) {430 testRunner.testComplete();431 } else {432 testRunner.testComplete(errorMessage);433 }434 } else if (chrome.send) {435 // For WebUI and v8 unit tests.436 chrome.send('testResult', result);437 } else if (window.domAutomationController.send) {438 // For extension tests.439 const valueResult = {'result': success, message: errorMessage};440 window.domAutomationController.send(JSON.stringify(valueResult));441 } else {442 assertNotReached('No test framework available');443 }444 errors.splice(0, errors.length);445 } else {446 console.warn('testIsDone already');447 }448}449/**450 * Converts each Error in |errors| to a suitable message, adding them to451 * |message|, and returns the message string.452 * @param {Array<Error>} errors Array of errors to add to |message|.453 * @param {string=} opt_message Message to append error messages to.454 * @return {string} |opt_message| + messages of all |errors|.455 */456function errorsToMessage(errors, opt_message) {457 var message = '';458 if (opt_message) {459 message += opt_message + '\n';460 }461 for (var i = 0; i < errors.length; ++i) {462 var errorMessage = errors[i].stack || errors[i].message;463 // Cast JSON.stringify to Function to avoid formal parameter mismatch.464 message += 'Failed: ' + currentTestFunction + '(' +465 currentTestArguments.map(/** @type{Function} */ (JSON.stringify)) +466 ')\n' + errorMessage;467 }468 return message;469}470/**471 * Returns [success, message] & clears |errors|.472 * @param {boolean=} errorsOk When true, errors are ok.473 *474 * No tuple type: b/131114945 (result should be {[boolean, string]}).475 * @return {Array}476 */477function testResult(errorsOk) {478 var result = [true, ''];479 if (errors.length) {480 result = [!!errorsOk, errorsToMessage(errors)];481 }482 return result;483}484// Asserts.485// Use the following assertions to verify a condition within a test.486/**487 * @param {boolean} value The value to check.488 * @param {string=} opt_message Additional error message.489 * @throws {Error}490 */491function assertTrue(value, opt_message) {492 chai.assert.isTrue(value, opt_message);493}494/**495 * @param {boolean} value The value to check.496 * @param {string=} opt_message Additional error message.497 * @throws {Error}498 */499function assertFalse(value, opt_message) {500 chai.assert.isFalse(value, opt_message);501}502/**503 * @param {number} value1 The first operand.504 * @param {number} value2 The second operand.505 * @param {string=} opt_message Additional error message.506 * @throws {Error}507 */508function assertGE(value1, value2, opt_message) {509 chai.expect(value1).to.be.at.least(value2, opt_message);510}511/**512 * @param {number} value1 The first operand.513 * @param {number} value2 The second operand.514 * @param {string=} opt_message Additional error message.515 * @throws {Error}516 */517function assertGT(value1, value2, opt_message) {518 chai.assert.isAbove(value1, value2, opt_message);519}520/**521 * @param {*} expected The expected value.522 * @param {*} actual The actual value.523 * @param {string=} opt_message Additional error message.524 * @throws {Error}525 */526function assertEquals(expected, actual, opt_message) {527 chai.assert.strictEqual(actual, expected, opt_message);528}529/**530 * @param {*} expected531 * @param {*} actual532 * {string=} opt_message533 * @throws {Error}534 */535function assertDeepEquals(expected, actual, opt_message) {536 chai.assert.deepEqual(actual, expected, opt_message);537}538/**539 * @param {number} value1 The first operand.540 * @param {number} value2 The second operand.541 * @param {string=} opt_message Additional error message.542 * @throws {Error}543 */544function assertLE(value1, value2, opt_message) {545 chai.expect(value1).to.be.at.most(value2, opt_message);546}547/**548 * @param {number} value1 The first operand.549 * @param {number} value2 The second operand.550 * @param {string=} opt_message Additional error message.551 * @throws {Error}552 */553function assertLT(value1, value2, opt_message) {554 chai.assert.isBelow(value1, value2, opt_message);555}556/**557 * @param {*} expected The expected value.558 * @param {*} actual The actual value.559 * @param {string=} opt_message Additional error message.560 * @throws {Error}561 */562function assertNotEquals(expected, actual, opt_message) {563 chai.assert.notStrictEqual(actual, expected, opt_message);564}565/**566 * @param {string=} opt_message Additional error message.567 * @throws {Error}568 */569function assertNotReached(opt_message) {570 chai.assert.fail(null, null, opt_message);571}572/**573 * @param {function()} testFunction574 * @param {(Function|string|RegExp)=} opt_expected_or_constructor The expected575 * Error constructor, partial or complete error message string, or RegExp to576 * test the error message.577 * @param {string=} opt_message Additional error message.578 * @throws {Error}579 */580function assertThrows(testFunction, opt_expected_or_constructor, opt_message) {581 // The implementation of assert.throws goes like:582 // function (fn, errt, errs, msg) {583 // if ('string' === typeof errt || errt instanceof RegExp) {584 // errs = errt;585 // errt = null;586 // }587 // ...588 // That is, if the second argument is string or RegExp, the type of the589 // exception is not checked: only the error message. This is achieved by590 // partially "shifting" parameters (the "additional error message" is not591 // shifted and will be lost). "Shifting" isn't a thing Closure understands, so592 // just cast to string.593 // TODO(crbug/1000989): Refactor this into something that makes sense when594 // tests are actually compiled and we can do that safely.595 chai.assert.throws(596 testFunction,597 /** @type{string} */ (opt_expected_or_constructor), opt_message);598}599/**600 * Creates a function based upon a function that throws an exception on601 * failure. The new function stuffs any errors into the |errors| array for602 * checking by runTest. This allows tests to continue running other checks,603 * while failing the overall test if any errors occurred.604 * @param {Function} assertFunc The function which may throw an Error.605 * @return {function(...*):boolean} A function that applies its arguments to606 * |assertFunc| and returns true if |assertFunc| passes.607 * @see errors608 * @see runTestFunction609 */610function createExpect(assertFunc) {611 return function() {612 try {613 assertFunc.apply(null, arguments);614 } catch (e) {615 errors.push(e);616 return false;617 }618 return true;619 };620}621/**622 * This is the starting point for tests run by WebUIBrowserTest. If an error623 * occurs, it reports a failure and a message created by joining individual624 * error messages. This supports sync tests and async tests by calling625 * testDone() when |isAsync| is not true, relying on async tests to call626 * testDone() when they complete.627 * @param {boolean} isAsync When false, call testDone() with the test result628 * otherwise only when assertions are caught.629 * @param {string} testFunction The function name to call.630 * @param {Array} testArguments The arguments to call |testFunction| with.631 * @return {boolean} true always to signal successful execution (but not632 * necessarily successful results) of this test.633 * @see errors634 * @see runTestFunction635 */636function runTest(isAsync, testFunction, testArguments) {637 // If waiting for user to attach a debugger, retry in 1 second.638 if (waitUser) {639 setTimeout(runTest, 1000, isAsync, testFunction, testArguments);640 return true;641 }642 // Avoid eval() if at all possible, since it will not work on pages643 // that have enabled content-security-policy.644 /** @type {?Function} */645 var testBody = this[testFunction]; // global object -- not a method.646 var testName = testFunction;647 // Depending on how we were called, |this| might not resolve to the global648 // context.649 if (testName === 'RUN_TEST_F' && testBody === undefined) {650 testBody = RUN_TEST_F;651 }652 if (typeof testBody === 'undefined') {653 testBody = /** @type{Function} */ (eval(testFunction));654 testName = testBody.toString();655 }656 if (testBody !== RUN_TEST_F) {657 console.log('Running test ' + testName);658 }659 // Async allow expect errors, but not assert errors.660 var result = runTestFunction(testFunction, testBody, testArguments, isAsync);661 if (!isAsync || !result[0]) {662 testDone(result);663 }664 return true;665}666/**667 * This is the guts of WebUIBrowserTest. It runs the test surrounded by an668 * expect to catch Errors. If |errors| is non-empty, it reports a failure and669 * a message by joining |errors|. Consumers can use this to use assert/expect670 * functions asynchronously, but are then responsible for reporting errors to671 * the browser themselves through testDone().672 * @param {string} testFunction The function name to report on failure.673 * @param {Function} testBody The function to call.674 * @param {Array} testArguments The arguments to call |testBody| with.675 * @param {boolean} onlyAssertFails When true, only assertions cause failing676 * testResult.677 *678 * No tuple type: b/131114945 (result should be {[boolean, string]}).679 * @return {Array} [test-succeeded, message-if-failed]680 * @see createExpect681 * @see testResult682 */683function runTestFunction(684 testFunction, testBody, testArguments, onlyAssertFails) {685 currentTestFunction = testFunction;686 currentTestArguments = testArguments;687 var ok = createExpect(testBody).apply(null, testArguments);688 return testResult(onlyAssertFails && ok);689}690/**691 * Creates a new test case for the given |testFixture| and |testName|. Assumes692 * |testFixture| describes a globally available subclass of type Test.693 * @param {string} testFixture The fixture for this test case.694 * @param {string} testName The name for this test case.695 * @return {TestCase} A newly created TestCase.696 */697function createTestCase(testFixture, testName) {698 var fixtureConstructor = this[testFixture];699 assertTrue(700 !!fixtureConstructor,701 `The testFixture \'${testFixture}\' was not found.`);702 var testBody = fixtureConstructor.testCaseBodies[testName];703 assertTrue(704 !!testBody, `Test \'${testName} was not found in \'${testFixture}\'.`);705 var fixture = new fixtureConstructor();706 fixture.name = testFixture;707 return new TestCase(testName, fixture, testBody);708}709/**710 * Used by WebUIBrowserTest to preload the javascript libraries at the711 * appropriate time for javascript injection into the current page. This712 * creates a test case and calls its preLoad for any early initialization such713 * as registering handlers before the page's javascript runs it's OnLoad714 * method. This is called before the page is loaded.715 * @param {string} testFixture The test fixture name.716 * @param {string} testName The test name.717 */718function preloadJavascriptLibraries(testFixture, testName) {719 currentTestCase = createTestCase(testFixture, testName);720 currentTestCase.preLoad();721}722/**723 * Sets |waitUser| to true so |runTest| function waits for user to attach a724 * debugger.725 */726function setWaitUser() {727 waitUser = true;728 exports.go = () => waitUser = false;729 console.log('Waiting for debugger...');730 console.log('Run: go() in the JS console when you are ready.');731}732/**733 * During generation phase, this outputs; do nothing at runtime.734 */735function GEN() {}736/**737 * During generation phase, this outputs; do nothing at runtime.738 */739function GEN_INCLUDE() {}740/**741 * At runtime, register the testName with a test fixture. Since this method742 * doesn't have a test fixture, create a dummy fixture to hold its |name|743 * and |testCaseBodies|.744 * @param {string} testCaseName The name of the test case.745 * @param {string} testName The name of the test function.746 * @param {Function} testBody The body to execute when running this test.747 */748function TEST(testCaseName, testName, testBody) {749 var fixtureConstructor = this[testCaseName];750 if (fixtureConstructor === undefined) {751 fixtureConstructor = function() {};752 this[testCaseName] = fixtureConstructor;753 fixtureConstructor.prototype = {754 __proto__: Test.prototype,755 name: testCaseName,756 };757 fixtureConstructor.testCaseBodies = {};758 }759 fixtureConstructor.testCaseBodies[testName] = testBody;760}761/**762 * At runtime, register the testName with its fixture. Stuff the |name| into763 * the |testFixture|'s prototype, if needed, and the |testCaseBodies| into its764 * constructor.765 * @param {string} testFixture The name of the test fixture class.766 * @param {string} testName The name of the test function.767 * @param {Function} testBody The body to execute when running this test.768 * @param {string=} opt_preamble C++ code to be generated before the test. Does769 * nothing here in the runtime phase.770 */771function TEST_F(testFixture, testName, testBody, opt_preamble) {772 var fixtureConstructor = this[testFixture];773 if (!fixtureConstructor.prototype.name) {774 fixtureConstructor.prototype.name = testFixture;775 }776 if (fixtureConstructor['testCaseBodies'] === undefined) {777 fixtureConstructor.testCaseBodies = {};778 }779 fixtureConstructor.testCaseBodies[testName] = testBody;780}781/**782 * Similar to TEST_F above but with a mandatory |preamble|.783 * @param {string} preamble C++ code to be generated before the test. Does784 * nothing here in the runtime phase.785 * @param {string} testFixture The name of the test fixture class.786 * @param {string} testName The name of the test function.787 * @param {Function} testBody The body to execute when running this test.788 */789function TEST_F_WITH_PREAMBLE(preamble, testFixture, testName, testBody) {790 TEST_F(testFixture, testName, testBody);791}792/**793 * RunJavascriptTestF uses this as the |testFunction| when invoking794 * runTest. If |currentTestCase| is non-null at this point, verify that795 * |testFixture| and |testName| agree with the preloaded values. Create796 * |currentTestCase|, if needed, run it, and clear the |currentTestCase|.797 * @param {string} testFixture The name of the test fixture class.798 * @param {string} testName The name of the test function.799 * @see preloadJavascriptLibraries800 * @see runTest801 */802function RUN_TEST_F(testFixture, testName) {803 if (!currentTestCase) {804 currentTestCase = createTestCase(testFixture, testName);805 }806 assertEquals(currentTestCase.name, testName);807 assertEquals(currentTestCase.fixture.name, testFixture);808 console.log('Running TestCase ' + testFixture + '.' + testName);809 currentTestCase.run();810}811/**812 * This Mock4JS matcher object pushes each |actualArgument| parameter to813 * match() calls onto |args|.814 * @param {Array} args The array to push |actualArgument| onto.815 * @param {Object} realMatcher The real matcher check arguments with.816 * @constructor817 */818function SaveMockArgumentMatcher(args, realMatcher) {819 this.arguments_ = args;820 this.realMatcher_ = realMatcher;821}822SaveMockArgumentMatcher.prototype = {823 /**824 * Holds the arguments to push each |actualArgument| onto.825 * @type {Array}826 * @private827 */828 arguments_: null,829 /**830 * The real Mock4JS matcher object to check arguments with.831 * @type {Object}832 */833 realMatcher_: null,834 /**835 * Pushes |actualArgument| onto |arguments_| and call |realMatcher_|. Clears836 * |arguments_| on non-match.837 * @param {*} actualArgument The argument to match and save.838 * @return {boolean} Result of calling the |realMatcher|.839 */840 argumentMatches: function(actualArgument) {841 this.arguments_.push(actualArgument);842 var match = this.realMatcher_.argumentMatches(actualArgument);843 if (!match) {844 this.arguments_.splice(0, this.arguments_.length);845 }846 return match;847 },848 /**849 * Proxy to |realMatcher_| for description.850 * @return {string} Description of this Mock4JS matcher.851 */852 describe: function() {853 return this.realMatcher_.describe();854 },855};856/**857 * Actions invoked by Mock4JS's "will()" syntax do not receive arguments from858 * the mocked method. This class works with SaveMockArgumentMatcher to save859 * arguments so that the invoked Action can pass arguments through to the860 * invoked function.861 * @constructor862 */863function SaveMockArguments() {864 this.arguments = [];865}866SaveMockArguments.prototype = {867 /**868 * Wraps the |realMatcher| with an object which will push its argument onto869 * |arguments| and call realMatcher.870 * @param {Object} realMatcher A Mock4JS matcher object for this argument.871 * @return {SaveMockArgumentMatcher} A new matcher which will push its872 * argument onto |arguments|.873 */874 match: function(realMatcher) {875 return new SaveMockArgumentMatcher(this.arguments, realMatcher);876 },877 /**878 * Remember the argument passed to this stub invocation.879 * @type {Array}880 */881 arguments: null,882};883/**884 * CallFunctionAction is provided to allow mocks to have side effects.885 * @param {Object} obj The object to set |this| to when calling |func_|.886 * @param {?SaveMockArguments} savedArgs when non-null, saved arguments are887 * passed to |func|.888 * @param {!Function} func The function to call.889 * @param {Array=} args Any arguments to pass to func.890 * @constructor891 */892function CallFunctionAction(obj, savedArgs, func, args) {893 /**894 * Set |this| to |obj_| when calling |func_|.895 * @type {?Object}896 */897 this.obj_ = obj;898 /**899 * The SaveMockArguments to hold arguments when invoking |func_|.900 * @type {?SaveMockArguments}901 * @private902 */903 this.savedArgs_ = savedArgs;904 /**905 * The function to call when invoked.906 * @type {!Function}907 * @private908 */909 this.func_ = func;910 /**911 * Arguments to pass to |func_| when invoked.912 * @type {!Array}913 */914 this.args_ = args || [];915}916CallFunctionAction.prototype = {917 /**918 * Accessor for |func_|.919 * @return {Function} The function to invoke.920 */921 get func() {922 return this.func_;923 },924 /**925 * Called by Mock4JS when using .will() to specify actions for stubs() or926 * expects(). Clears |savedArgs_| so it can be reused.927 * @return The results of calling |func_| with the concatenation of928 * |savedArgs_| and |args_|.929 */930 invoke: function() {931 var prependArgs = [];932 if (this.savedArgs_) {933 prependArgs =934 this.savedArgs_.arguments.splice(0, this.savedArgs_.arguments.length);935 }936 return this.func.apply(this.obj_, prependArgs.concat(this.args_));937 },938 /**939 * Describe this action to Mock4JS.940 * @return {string} A description of this action.941 */942 describe: function() {943 return 'calls the given function with saved arguments and ' + this.args_;944 }945};946/**947 * Syntactic sugar for use with will() on a Mock4JS.Mock.948 * @param {SaveMockArguments} savedArgs Arguments saved with this object949 * are passed to |func|.950 * @param {!Function} func The function to call when the method is invoked.951 * @param {...*} var_args Arguments to pass when calling func.952 * @return {CallFunctionAction} Action for use in will.953 */954function callFunctionWithSavedArgs(savedArgs, func, var_args) {955 return new CallFunctionAction(956 null, savedArgs, func, Array.prototype.slice.call(arguments, 2));957}958/**959 * When to call testDone().960 * @enum {number}961 */962var WhenTestDone = {963 /**964 * Default for the method called.965 */966 DEFAULT: -1,967 /**968 * Never call testDone().969 */970 NEVER: 0,971 /**972 * Call testDone() on assert failure.973 */974 ASSERT: 1,975 /**976 * Call testDone() if there are any assert or expect failures.977 */978 EXPECT: 2,979 /**980 * Always call testDone().981 */982 ALWAYS: 3,983};984/**985 * Runs all |actions|.986 * @param {boolean} isAsync When true, call testDone() on Errors.987 * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate988 * time.989 * @param {Array<Object>} actions Actions to run.990 * @constructor991 */992function RunAllAction(isAsync, whenTestDone, actions) {993 this.isAsync_ = isAsync;994 this.whenTestDone_ = whenTestDone;995 this.actions_ = actions;996}997RunAllAction.prototype = {998 /**999 * When true, call testDone() on Errors.1000 * @type {boolean}1001 * @private1002 */1003 isAsync_: false,1004 /**1005 * Call testDone() at appropriate time.1006 * @type {WhenTestDone}1007 * @private1008 * @see WhenTestDone1009 */1010 whenTestDone_: WhenTestDone.ASSERT,1011 /**1012 * Holds the actions to execute when invoked.1013 * @type {Array}1014 * @private1015 */1016 actions_: null,1017 /**1018 * Runs all |actions_|, returning the last one. When running in sync mode,1019 * throws any exceptions to be caught by runTest() or1020 * runTestFunction(). Call testDone() according to |whenTestDone_| setting.1021 */1022 invoke: function() {1023 try {1024 var result;1025 for (var i = 0; i < this.actions_.length; ++i) {1026 result = this.actions_[i].invoke();1027 }1028 if ((this.whenTestDone_ === WhenTestDone.EXPECT && errors.length) ||1029 this.whenTestDone_ === WhenTestDone.ALWAYS) {1030 testDone();1031 }1032 return result;1033 } catch (e) {1034 if (!(e instanceof Error)) {1035 e = new Error(e.toString());1036 }1037 if (!this.isAsync_) {1038 throw e;1039 }1040 errors.push(e);1041 if (this.whenTestDone_ !== WhenTestDone.NEVER) {1042 testDone();1043 }1044 }1045 },1046 /**1047 * Describe this action to Mock4JS.1048 * @return {string} A description of this action.1049 */1050 describe: function() {1051 return 'Calls all actions: ' + this.actions_;1052 },1053};1054/**1055 * Syntactic sugar for use with will() on a Mock4JS.Mock.1056 * @param {...*} var_args Actions to run.1057 * @return {RunAllAction} Action for use in will.1058 */1059function runAllActions(var_args) {1060 return new RunAllAction(1061 false, WhenTestDone.NEVER, Array.prototype.slice.call(arguments));1062}1063/**1064 * Syntactic sugar for use with will() on a Mock4JS.Mock.1065 * @param {WhenTestDone} whenTestDone Call testDone() at the appropriate1066 * time.1067 * @param {...*} var_args Actions to run.1068 * @return {RunAllAction} Action for use in will.1069 */1070function runAllActionsAsync(whenTestDone, var_args) {1071 return new RunAllAction(1072 true, whenTestDone, Array.prototype.slice.call(arguments, 1));1073}1074/**1075 * Exports assertion methods. All assertion methods delegate to the chai.js1076 * assertion library.1077 */1078function exportChaiAsserts() {1079 exports.assertTrue = assertTrue;1080 exports.assertFalse = assertFalse;1081 exports.assertGE = assertGE;1082 exports.assertGT = assertGT;1083 exports.assertEquals = assertEquals;1084 exports.assertDeepEquals = assertDeepEquals;1085 exports.assertLE = assertLE;1086 exports.assertLT = assertLT;1087 exports.assertNotEquals = assertNotEquals;1088 exports.assertNotReached = assertNotReached;1089 exports.assertThrows = assertThrows;1090}1091/**1092 * Exports expect methods. 'expect*' methods allow tests to run until the end1093 * even in the presence of failures.1094 */1095function exportExpects() {1096 exports.expectTrue = createExpect(assertTrue);1097 exports.expectFalse = createExpect(assertFalse);1098 exports.expectGE = createExpect(assertGE);1099 exports.expectGT = createExpect(assertGT);1100 exports.expectEquals = createExpect(assertEquals);1101 exports.expectDeepEquals = createExpect(assertDeepEquals);1102 exports.expectLE = createExpect(assertLE);1103 exports.expectLT = createExpect(assertLT);1104 exports.expectNotEquals = createExpect(assertNotEquals);1105 exports.expectNotReached = createExpect(assertNotReached);1106 exports.expectThrows = createExpect(assertThrows);1107}1108/**1109 * Exports methods related to Mock4JS mocking.1110 */1111function exportMock4JsHelpers() {1112 exports.callFunctionWithSavedArgs = callFunctionWithSavedArgs;1113 exports.SaveMockArguments = SaveMockArguments;1114}1115// Exports.1116testing.Test = Test;1117exports.testDone = testDone;1118exportChaiAsserts();1119exportExpects();1120exportMock4JsHelpers();...

Full Screen

Full Screen

basic.spec.js

Source:basic.spec.js Github

copy

Full Screen

...62 resolve(stats)63 })64 })65}66function createExpect(content, module) {67 return JSON.stringify({68 source: content,69 query: module ? { module: true } : '',70 })71}72function readOutput() {73 return fs.readFile(path.join(__dirname, 'dist/bundle.js'), { encoding: 'utf-8' })74}75/**76 * Create test cases with different webpack77 */78function createTestWithWebpack(webpack) {79 return () => {80 describe('ImportDeclaration', () => {81 it('add mark when has specifiers', async () => {82 await buildWithWebpack(webpack, {83 entry: 'import-modules-dep.js',84 plugins: [new AutoCSSModulesWebpackPlugin()],85 })86 expect(await readOutput()).toContain(createExpect(LESS_CONTENT, true))87 })88 it('not add mark when no specifiers', async () => {89 await buildWithWebpack(webpack, {90 entry: 'import-dep.js',91 plugins: [new AutoCSSModulesWebpackPlugin()],92 })93 expect(await readOutput()).toContain(createExpect(LESS_CONTENT, false))94 })95 })96 describe('CommonJs Require', () => {97 it('add mark when assign result to a variable', async () => {98 await buildWithWebpack(webpack, {99 entry: 'require-modules-dep.js',100 plugins: [new AutoCSSModulesWebpackPlugin()],101 })102 expect(await readOutput()).toContain(createExpect(LESS_CONTENT, true))103 })104 it('not add mark when not assign to a variable', async () => {105 await buildWithWebpack(webpack, {106 entry: 'require-dep.js',107 plugins: [new AutoCSSModulesWebpackPlugin()],108 })109 expect(await readOutput()).toContain(createExpect(LESS_CONTENT, false))110 })111 it('works with single wrapped require call', async () => {112 await buildWithWebpack(webpack, {113 entry: 'require-wrap-function.js',114 plugins: [new AutoCSSModulesWebpackPlugin()],115 })116 expect(await readOutput()).toContain(createExpect(LESS_CONTENT, true))117 })118 it('works with require inside MemberExpression', async () => {119 await buildWithWebpack(webpack, {120 entry: 'require-wrap-member.js',121 plugins: [new AutoCSSModulesWebpackPlugin()],122 })123 expect(await readOutput()).toContain(createExpect(LESS_CONTENT, true))124 })125 })126 it('works with other queryFlag', async () => {127 await buildWithWebpack(128 webpack,129 {130 entry: 'import-modules-dep.js',131 plugins: [new AutoCSSModulesWebpackPlugin({ queryFlag: 'my_custom_flag' })],132 },133 { queryFlag: 'my_custom_flag' }134 )135 expect(await readOutput()).toContain(createExpect(LESS_CONTENT, true))136 })137 it('not works when queryFlag mismatch', async () => {138 await buildWithWebpack(webpack, {139 entry: 'import-modules-dep.js',140 plugins: [new AutoCSSModulesWebpackPlugin({ queryFlag: 'my_custom_flag' })],141 })142 expect(await readOutput()).toContain(createExpect(LESS_CONTENT, false))143 })144 it('works with other extname', async () => {145 await buildWithWebpack(146 webpack,147 {148 entry: 'import-modules-dep.js',149 plugins: [new AutoCSSModulesWebpackPlugin({ extraExtnames: ['.other'] })],150 },151 {152 replace: { from: '\\.less', to: '.other' },153 }154 )155 expect(await readOutput()).toContain(createExpect(OTHER_CONTENT, true))156 })157 it('not works when extname not in extname list', async () => {158 await buildWithWebpack(159 webpack,160 {161 entry: 'import-modules-dep.js',162 plugins: [new AutoCSSModulesWebpackPlugin()],163 },164 {165 replace: { from: '\\.less', to: '.other' },166 }167 )168 expect(await readOutput()).toContain(createExpect(OTHER_CONTENT, false))169 })170 }171}172describe('AutoCSSModulesWebpackPlugin', () => {173 beforeEach(() => fs.remove(OUTPUT_DIR))174 describe('webpack4', createTestWithWebpack(webpack4))175 describe('webpack5', createTestWithWebpack(webpack5))...

Full Screen

Full Screen

test.stream-expect.js

Source:test.stream-expect.js Github

copy

Full Screen

...18 it('should expose the child process', function() {19 assert.ok(exp.child.pid)20 })21 })22 describe('#createExpect()', function() {23 it('should return an instance of Expect', function() {24 var child = spawn('node', [fixture])25 var exp = expect.createExpect(child.stdout, child.stdin)26 assert.ok(exp instanceof Expect)27 })28 it('accepts the createExpect(ReadStream, WriteStream, options) signature', function() {29 var readStream = {30 on : function() {},31 readable : true32 }33 var writeStream = {34 writeable : true,35 write : function() {}36 }37 var exp = expect.createExpect(readStream, writeStream, { timeout: 1000 })38 assert.equal(exp._rStream, readStream)39 assert.equal(exp._wStream, writeStream)40 assert.equal(exp.timeout, 1000)41 })42 it('accepts the createExpect(stream, options) signature', function() {43 var stream = {44 on : function() {},45 writeable : true,46 readable : true,47 write : function() {}48 }49 var exp = expect.createExpect(stream, { timeout: 1000 })50 assert.equal(exp._rStream, stream)51 assert.equal(exp._wStream, stream)52 assert.equal(exp.timeout, 1000)53 })54 it('accepts the createExpect(stream) signature', function() {55 var stream = {56 on : function() {},57 writeable : true,58 readable : true59 }60 var exp = expect.createExpect(stream)61 assert.equal(exp._rStream, stream)62 assert.equal(exp._wStream, stream)63 })64 })65 describe('#expect()', function() {66 it('should return an Expect object', function() {67 var obj = exp.expect(/./, function(){})68 assert.ok(obj instanceof Expect)69 })70 it('should call callback(null) on pattern match', function(done) {71 exp.expect(/ipsum/, function(err) {72 assert.strictEqual(null, err)73 done()74 })...

Full Screen

Full Screen

pmWmUpdate_spec.js

Source:pmWmUpdate_spec.js Github

copy

Full Screen

1/**2 * Created by johngossett on 5/23/17.3 */4var frisby = require('frisby');5var moment = require('moment');6var oDate = moment().utc().format("YYYY-MM-DDTHH:mm:ss") + ".000Z";7var utility = require('./utility.js').utility;8var url = process.env['url'];9var debug = process.env['debug'];10var pmToPost = function (details) {11 return {12 "name": "SAC Units", "client": "uM5jSPfAJtAtezipe", "site": "P6J6b6SWL2hK9DHgB",13 "assettype": "3dXwbXpdi7nxpbXaX", "isLifeSafety": details[0],14 "durationEstimate": {"minutes": "3"}, "schedule": {15 "frequency": details[1], "startDate": details[2], "dueWithin": details[3],16 "assignee": "LH8J4cELRRsW8Ggu2", "assigneeTeam": "idTqTEP3b3uYJfdAa", "type": details[4]17 }, "steps": [{18 "step_id": "yca7wP98jo5P27MdB",19 "description": "Check air cleaner filter; change if dirty"20 }], "assetsOrLocs": utility.assetLocs(1,details[2])21 }22};23var pmExpect = function (id, details) {24 return {25 "status": "success", "data": {26 "_id": id, "name": "SAC Units", "client": "uM5jSPfAJtAtezipe",27 "site": "P6J6b6SWL2hK9DHgB", "assettype": "3dXwbXpdi7nxpbXaX",28 "isLifeSafety": details[0], "durationEstimate": {29 "minutes": "3"30 }, "schedule": {31 "frequency": details[1], "startDate": details[2], "dueWithin": details[3],32 "assignee": "LH8J4cELRRsW8Ggu2", "assigneeTeam": "idTqTEP3b3uYJfdAa",33 "type": details[4]34 }35 }36 }37};38var pmUpdate = function (details) {39 return {40 "name": "SAC Units", "isLifeSafety": details[0], "durationEstimate": {"minutes": "3"},41 "schedule": {42 "frequency": details[1], "startDate": details[2], "dueWithin": details[3],43 "assignee": "LH8J4cELRRsW8Ggu2", "assigneeTeam": "idTqTEP3b3uYJfdAa", "type": details[4]44 }, "steps": [{45 "step_id": "yca7wP98jo5P27MdB",46 "description": "Check air cleaner filter; change if dirty"47 }],48 "assetsOrLocs": utility.assetLocs(2,details[2])49 }50};51var taskJson = function (id) {52 return {53 "name": "SAC Units", "client": "uM5jSPfAJtAtezipe", "site": "P6J6b6SWL2hK9DHgB",54 "assignee": {55 "user_id": "LH8J4cELRRsW8Ggu2", "name": "Arturo Estrada",56 "description": "hm35@localhost.com"57 }, "assigneeTeam": {58 "team_id": "idTqTEP3b3uYJfdAa", "name": "General Mechanic"59 }, "procedure": id, "isBlocked": false, "asset": "kgB3L7RCmT5Lc2W7X", "steps": [{60 "step_id": "yca7wP98jo5P27MdB",61 "description": "Check air cleaner filter; change if dirty"62 }], "asset": "kgB3L7RCmT5Lc2W7X", "durationEstimate": {63 "minutes": "3"64 }, "steps": [{65 "step_id": "yca7wP98jo5P27MdB",66 "description": "Check air cleaner filter; change if dirty"67 }]68 }69};70describe('pm tests', function () {71 it('can post and validate a monthly pm due ', function () {72 var createExpect = utility.expectArray(31, 'M', 0,oDate);73 var dueExpect = utility.dueDateArray(createExpect, 'w', 1);74 var dueDate = utility.now(0, oDate);75 var pmDetails = [false, "Weekly", dueDate, {"weeks": 1}, "fixed",4];76 var pmUpdateDetails = [true, "Monthly", dueDate, {"weeks": 1}, "fixed",2,dueExpect,createExpect];77 var timeFrame = utility.now(30, oDate);78 utility.updateScenario('pm', pmDetails, pmToPost, pmExpect, pmUpdateDetails, pmUpdate, pmExpect, taskJson, timeFrame)79 });...

Full Screen

Full Screen

expect.js

Source:expect.js Github

copy

Full Screen

...41 return matchers42 }43 return {44 get not() {45 return createExpect(received, true)46 },47 ...matchers48 }49}50const expect = (received) => createExpect(received)...

Full Screen

Full Screen

create-expect.js

Source:create-expect.js Github

copy

Full Screen

1"use strict";2var expectImpl = require("./expect");3function createExpect(referee) {4 function expect() {5 expectImpl.init(referee);6 return expectImpl.apply(referee, arguments);7 }8 return expect;9}...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

1import {clone as createExpect} from 'unexpected';2import unexpectedSinon from 'unexpected-sinon';3export const expect = createExpect();4expect.use(unexpectedSinon);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.click('text=Docs');7 await page.click('text=API');8 await page.click('text=class Playwright');9 await page.click('text=Internal API');10 await page.click('text=createExpect');11 await page.fill('input[name="q"]', 'createExpect');12 await page.press('input[name="q"]', 'Enter');13 await page.click('text=class Playwright');14 await page.click('text=Internal API');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { createExpect } = require('@playwright/test');2const expect = createExpect();3test('My Test', async ({ page }) => {4 expect(await page.title()).toBe('Playwright');5});6test('My Test', async ({ page }) => {7 expect(await page.title()).toBe('Playwright');8});9test('My Test', async ({ page }) => {10 expect(await page.title()).toBe('Playwright');11});12test('My Test', async ({ page }) => {13 expect(await page.title()).toBe('Playwright');14});15test('My Test', async ({ page }) => {16 expect(await page.title()).toBe('Playwright');17});18test('My Test', async ({ page }) => {19 expect(await page.title()).toBe('Playwright');20});21test('My Test', async ({ page }) => {22 expect(await page.title()).toBe('Playwright');23});24test('My Test', async ({ page }) => {25 expect(await page.title()).toBe('Playwright');26});27test('My Test', async ({ page }) => {28 expect(await page.title()).toBe('Playwright');29});30test('My Test', async ({ page }) => {31 expect(await page.title()).toBe('Playwright');32});33test('My Test',

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful