Best JavaScript code snippet using playwright-internal
test_json3.js
Source:test_json3.js  
...54  };55  // Tests56  // -----57  testSuite.addTest("`parse`: Empty Source Strings", function () {58    this.parseError("", "Empty JSON source string");59    this.parseError("\n\n\r\n", "Source string containing only line terminators");60    this.parseError(" ", "Source string containing a single space character");61    this.parseError(" ", "Source string containing multiple space characters");62    this.done(4);63  });64  testSuite.addTest("`parse`: Whitespace", function (test) {65    // The only valid JSON whitespace characters are tabs, spaces, and line66    // terminators. All other Unicode category `Z` (`Zs`, `Zl`, and `Zp`)67    // characters are invalid (note that the `Zs` category includes the68    // space character).69    var characters = ["{\u00a0}", "{\u1680}", "{\u180e}", "{\u2000}", "{\u2001}",70      "{\u2002}", "{\u2003}", "{\u2004}", "{\u2005}", "{\u2006}", "{\u2007}",71      "{\u2008}", "{\u2009}", "{\u200a}", "{\u202f}", "{\u205f}", "{\u3000}",72      "{\u2028}", "{\u2029}"];73    Spec.forEach(characters, function (value) {74      test.parseError(value, "Source string containing an invalid Unicode whitespace character");75    });76    this.parseError("{\u000b}", "Source string containing a vertical tab");77    this.parseError("{\u000c}", "Source string containing a form feed");78    this.parseError("{\ufeff}", "Source string containing a byte-order mark");79    this.parses({}, "{\r\n}", "Source string containing a CRLF line ending");80    this.parses({}, "{\n\n\r\n}", "Source string containing multiple line terminators");81    this.parses({}, "{\t}", "Source string containing a tab character");82    this.parses({}, "{ }", "Source string containing a space character");83    this.done(26);84  });85  testSuite.addTest("`parse`: Octal Values", function (test) {86    // `08` and `018` are invalid octal values.87    Spec.forEach(["00", "01", "02", "03", "04", "05", "06", "07", "010", "011", "08", "018"], function (value) {88      test.parseError(value, "Octal literal");89      test.parseError("-" + value, "Negative octal literal");90      test.parseError('"\\' + value + '"', "Octal escape sequence in a string");91      test.parseError('"\\x' + value + '"', "Hex escape sequence in a string");92    });93    this.done(48);94  });95  testSuite.addTest("`parse`: Numeric Literals", function () {96    this.parses(100, "100", "Integer");97    this.parses(-100, "-100", "Negative integer");98    this.parses(10.5, "10.5", "Float");99    this.parses(-3.141, "-3.141", "Negative float");100    this.parses(0.625, "0.625", "Decimal");101    this.parses(-0.03125, "-0.03125", "Negative decimal");102    this.parses(1000, "1e3", "Exponential");103    this.parses(100, "1e+2", "Positive exponential");104    this.parses(-0.01, "-1e-2", "Negative exponential");105    this.parses(3125, "0.03125e+5", "Decimalized exponential");106    this.parses(100, "1E2", "Case-insensitive exponential delimiter");107    this.parseError("+1", "Leading `+`");108    this.parseError("1.", "Trailing decimal point");109    this.parseError(".1", "Leading decimal point");110    this.parseError("1e", "Missing exponent");111    this.parseError("1e-", "Missing signed exponent");112    this.parseError("--1", "Leading `--`");113    this.parseError("1-+", "Trailing `-+`");114    this.parseError("0xaf", "Hex literal");115    // The native `JSON.parse` implementation in IE 9 allows this syntax, but116    // the feature tests should detect the broken implementation.117    this.parseError("- 5", "Invalid negative sign");118    this.done(20);119  });120  testSuite.addTest("`parse`: String Literals", function (test) {121    var expected = 48, controlCharacters = ["\u0001", "\u0002", "\u0003",122      "\u0004", "\u0005", "\u0006", "\u0007", "\b", "\t", "\n", "\u000b", "\f",123      "\r", "\u000e", "\u000f", "\u0010", "\u0011", "\u0012", "\u0013",124      "\u0014", "\u0015", "\u0016", "\u0017", "\u0018", "\u0019", "\u001a",125      "\u001b", "\u001c", "\u001d", "\u001e", "\u001f"];126    // Opera 7 discards null characters in strings.127    if ("\0".length) {128      expected += 1;129      controlCharacters.push("\u0000");130    }131    this.parses("value", '"value"', "Double-quoted string literal");132    this.parses("", '""', "Empty string literal");133    this.parses("\u2028", '"\\u2028"', "String containing an escaped Unicode line separator");134    this.parses("\u2029", '"\\u2029"', "String containing an escaped Unicode paragraph separator");135    // ExtendScript doesn't handle surrogate pairs correctly; attempting to136    // parse `"\ud834\udf06"` will throw an uncatchable error (issue #29).137    this.parses("\ud834\udf06", '"\ud834\udf06"', "String containing an unescaped Unicode surrogate pair");138    this.parses("\u0001", '"\\u0001"', "String containing an escaped ASCII control character");139    this.parses("\b", '"\\b"', "String containing an escaped backspace");140    this.parses("\f", '"\\f"', "String containing an escaped form feed");141    this.parses("\n", '"\\n"', "String containing an escaped line feed");142    this.parses("\r", '"\\r"', "String containing an escaped carriage return");143    this.parses("\t", '"\\t"', "String containing an escaped tab");144    this.parses("hello/world", '"hello\\/world"', "String containing an escaped solidus");145    this.parses("hello\\world", '"hello\\\\world"', "String containing an escaped reverse solidus");146    this.parses("hello\"world", '"hello\\"world"', "String containing an escaped double-quote character");147    this.parseError("'hello'", "Single-quoted string literal");148    this.parseError('"\\x61"', "String containing a hex escape sequence");149    this.parseError('"hello \r\n world"', "String containing an unescaped CRLF line ending");150    Spec.forEach(controlCharacters, function (value) {151      test.parseError('"' + value + '"', "String containing an unescaped ASCII control character");152    });153    this.done(expected);154  });155  testSuite.addTest("`parse`: Array Literals", function () {156    this.parseError("[1, 2, 3,]", "Trailing comma in array literal");157    this.parses([1, 2, [3, [4, 5]], 6, [true, false], [null], [[]]], "[1, 2, [3, [4, 5]], 6, [true, false], [null], [[]]]", "Nested arrays");158    this.parses([{}], "[{}]", "Array containing empty object literal");159    this.parses([100, true, false, null, {"a": ["hello"], "b": ["world"]}, [0.01]], "[1e2, true, false, null, {\"a\": [\"hello\"], \"b\": [\"world\"]}, [1e-2]]", "Mixed array");160    this.done(4);161  });162  testSuite.addTest("`parse`: Object Literals", function () {163    this.parses({"hello": "world"}, "{\"hello\": \"world\"}", "Object literal containing one member");164    this.parses({"hello": "world", "foo": ["bar", true], "fox": {"quick": true, "purple": false}}, "{\"hello\": \"world\", \"foo\": [\"bar\", true], \"fox\": {\"quick\": true, \"purple\": false}}", "Object literal containing multiple members");165    this.parseError("{key: 1}", "Unquoted identifier used as a property name");166    this.parseError("{false: 1}", "`false` used as a property name");167    this.parseError("{true: 1}", "`true` used as a property name");168    this.parseError("{null: 1}", "`null` used as a property name");169    this.parseError("{'key': 1}", "Single-quoted string used as a property name");170    this.parseError("{1: 2, 3: 4}", "Number used as a property name");171    this.parseError("{\"hello\": \"world\", \"foo\": \"bar\",}", "Trailing comma in object literal");172    this.done(9);173  });174  // JavaScript expressions should never be evaluated, as JSON 3 does not use175  // `eval`.176  testSuite.addTest("`parse`: Invalid Expressions", function (test) {177    Spec.forEach(["1 + 1", "1 * 2", "var value = 123;", "{});value = 123;({}", "call()", "1, 2, 3, \"value\""], function (expression) {178      test.parseError(expression, "Source string containing a JavaScript expression");179    });180    this.done(6);181  });182  testSuite.addTest("`stringify` and `parse`: Optional Arguments", function () {183    this.parses({"a": 1, "b": 16}, '{"a": 1, "b": "10000"}', "Callback function provided", function (key, value) {184      return typeof value == "string" ? parseInt(value, 2) : value;185    });186    this.serializes("{\n  \"bar\": 456\n}", {"foo": 123, "bar": 456}, "Object; optional `filter` and `whitespace` arguments", ["bar"], 2);187    // Test adapted from the Opera JSON test suite via Ken Snyder.188    // See http://testsuites.opera.com/JSON/correctness/scripts/045.js189    // The regular expression is necessary because the ExtendScript engine190    // only approximates pi to 14 decimal places (ES 3 and ES 5 approximate191    // pi to 15 places).192    this.ok(/^\{"PI":3\.\d{14,15}\}$/.test(JSON.stringify(Math, ["PI"])), "List of non-enumerable property names specified as the `filter` argument");193    this.equal(3, JSON.parse("[1, 2, 3]", function (key, value) {194      if (typeof value == "object" && value) {195        return value;196      }197    }).length, "Issue #10: `walk` should not use `splice` when removing an array element");198    this.done(4);199  });200  testSuite.addTest("`stringify`", function () {201    var expected = 29;202    // Special values.203    this.serializes("null", null, "`null` is represented literally");204    this.serializes("null", 1 / 0, "`Infinity` is serialized as `null`");205    this.serializes("null", 0 / 0, "`NaN` is serialized as `null`");206    this.serializes("null", -1 / 0, "`-Infinity` is serialized as `null`");207    this.serializes("true", true, "Boolean primitives are represented literally");208    this.serializes("false", new Boolean(false), "Boolean objects are represented literally");209    this.serializes('"\\\\\\"How\\bquickly\\tdaft\\njumping\\fzebras\\rvex\\""', new String('\\"How\bquickly\tdaft\njumping\fzebras\rvex"'), "All control characters in strings are escaped");210    this.serializes("[false,1,\"Kit\"]", [new Boolean, new Number(1), new String("Kit")], "Arrays are serialized recursively");211    this.serializes("[null]", [void 0], "`[undefined]` is serialized as `[null]`");212    // Property enumeration is implementation-dependent.213    var value = {214      "jdalton": ["John-David", 29],215      "kitcambridge": ["Kit", 18],216      "mathias": ["Mathias", 23]217    };218    this.parses(value, JSON.stringify(value), "Objects are serialized recursively");219    // Complex cyclic structures.220    value = { "foo": { "b": { "foo": { "c": { "foo": null} } } } };221    this.serializes('{"foo":{"b":{"foo":{"c":{"foo":null}}}}}', value, "Nested objects containing identically-named properties should serialize correctly");222    var S = [], N = {};223    S.push(N, N);224    this.serializes('[{},{}]', S, "Objects containing duplicate references should not throw a `TypeError`");225    value.foo.b.foo.c.foo = value;226    this.cyclicError(value, "Objects containing complex circular references should throw a `TypeError`");227    // Sparse arrays.228    value = [];229    value[5] = 1;230    this.serializes("[null,null,null,null,null,1]", value, "Sparse arrays should serialize correctly");231    // Dates.232    this.serializes('"1994-07-03T00:00:00.000Z"', new Date(Date.UTC(1994, 6, 3)), "Dates should be serialized according to the simplified date time string format");233    this.serializes('"1993-06-02T02:10:28.224Z"', new Date(Date.UTC(1993, 5, 2, 2, 10, 28, 224)), "The date time string should conform to the format outlined in the spec");234    this.serializes('"-271821-04-20T00:00:00.000Z"', new Date(-8.64e15), "The minimum valid date value should serialize correctly");235    this.serializes('"+275760-09-13T00:00:00.000Z"', new Date(8.64e15), "The maximum valid date value should serialize correctly");236    this.serializes('"+010000-01-01T00:00:00.000Z"', new Date(Date.UTC(10000, 0, 1)), "https://bugs.ecmascript.org/show_bug.cgi?id=119");237    // Tests based on research by @Yaffle. See kriskowal/es5-shim#111.238    this.serializes('"1969-12-31T23:59:59.999Z"', new Date(-1), "Millisecond values < 1000 should be serialized correctly");239    this.serializes('"-000001-01-01T00:00:00.000Z"', new Date(-621987552e5), "Years prior to 0 should be serialized as extended years");240    this.serializes('"+010000-01-01T00:00:00.000Z"', new Date(2534023008e5), "Years after 9999 should be serialized as extended years");241    this.serializes('"-109252-01-01T10:37:06.708Z"', new Date(-3509827334573292), "Issue #4: Opera > 9.64 should correctly serialize a date with a year of `-109252`");242    // Opera 7 normalizes dates with invalid time values to represent the243    // current date.244    value = new Date("Kit");245    if (!isFinite(value)) {246      expected += 1;247      this.serializes("null", value, "Invalid dates should serialize as `null`");248    }249    // Additional arguments.250    this.serializes("[\n  1,\n  2,\n  3,\n  [\n    4,\n    5\n  ]\n]", [1, 2, 3, [4, 5]], "Nested arrays; optional `whitespace` argument", null, "  ");251    this.serializes("[]", [], "Empty array; optional string `whitespace` argument", null, "  ");252    this.serializes("{}", {}, "Empty object; optional numeric `whitespace` argument", null, 2);253    this.serializes("[\n  1\n]", [1], "Single-element array; optional numeric `whitespace` argument", null, 2);254    this.serializes("{\n  \"foo\": 123\n}", { "foo": 123 }, "Single-member object; optional string `whitespace` argument", null, "  ");255    this.serializes("{\n  \"foo\": {\n    \"bar\": [\n      123\n    ]\n  }\n}", {"foo": {"bar": [123]}}, "Nested objects; optional numeric `whitespace` argument", null, 2);256    this.done(expected);257  });258  /*259   * The following tests are adapted from the ECMAScript 5 Conformance Suite.260   * Copyright 2009, Microsoft Corporation. Distributed under the New BSD License.261   *262   * Redistribution and use in source and binary forms, with or without263   * modification, are permitted provided that the following conditions are met:264   *265   *   - Redistributions of source code must retain the above copyright notice,266   *     this list of conditions and the following disclaimer.267   *   - Redistributions in binary form must reproduce the above copyright notice,268   *     this list of conditions and the following disclaimer in the documentation269   *     and/or other materials provided with the distribution.270   *   - Neither the name of Microsoft nor the names of its contributors may be271   *     used to endorse or promote products derived from this software without272   *     specific prior written permission.273   *274   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"275   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE276   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE277   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE278   * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR279   * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF280   * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS281   * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN282   * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)283   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE284   * POSSIBILITY OF SUCH DAMAGE.285  */286  testSuite.addTest("ECMAScript 5 Conformance", function () {287    var value = { "a1": { "b1": [1, 2, 3, 4], "b2": { "c1": 1, "c2": 2 } }, "a2": "a2" };288    // Section 15.12.1.1: The JSON Grammar.289    // ------------------------------------290    // Tests 15.12.1.1-0-1 thru 15.12.1.1-0-8.291    this.parseError("12\t\r\n 34", "Valid whitespace characters may not separate two discrete tokens");292    this.parseError("\u000b1234", "The vertical tab is not a valid whitespace character");293    this.parseError("\u000c1234", "The form feed is not a valid whitespace character");294    this.parseError("\u00a01234", "The non-breaking space is not a valid whitespace character");295    this.parseError("\u200b1234", "The zero-width space is not a valid whitespace character");296    this.parseError("\ufeff1234", "The byte order mark (zero-width non-breaking space) is not a valid whitespace character");297    this.parseError("\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u30001234", "Other Unicode category `Z` characters are not valid whitespace characters");298    this.parseError("\u2028\u20291234", "The line (U+2028) and paragraph (U+2029) separators are not valid whitespace characters");299    // Test 15.12.1.1-0-9.300    this.parses({ "property": {}, "prop2": [true, null, 123.456] },301      '\t\r \n{\t\r \n' +302      '"property"\t\r \n:\t\r \n{\t\r \n}\t\r \n,\t\r \n' +303      '"prop2"\t\r \n:\t\r \n' +304        '[\t\r \ntrue\t\r \n,\t\r \nnull\t\r \n,123.456\t\r \n]' +305      '\t\r \n}\t\r \n',306    "Valid whitespace characters may precede and follow all tokens");307    // Tests 15.12.1.1-g1-1 thru 15.12.1.1-g1-4.308    this.parses(1234, "\t1234", "Leading tab characters should be ignored");309    this.parseError("12\t34", "A tab character may not separate two disparate tokens");310    this.parses(1234, "\r1234", "Leading carriage returns should be ignored");311    this.parseError("12\r34", "A carriage return may not separate two disparate tokens");312    this.parses(1234, "\n1234", "Leading line feeds should be ignored");313    this.parseError("12\n34", "A line feed may not separate two disparate tokens");314    this.parses(1234, " 1234", "Leading space characters should be ignored");315    this.parseError("12 34", "A space character may not separate two disparate tokens");316    // Tests 15.12.1.1-g2-1 thru 15.12.1.1-g2-5.317    this.parses("abc", '"abc"', "Strings must be enclosed in double quotes");318    this.parseError("'abc'", "Single-quoted strings are not permitted");319    // Note: the original test 15.12.1.1-g2-3 (`"\u0022abc\u0022"`) is incorrect,320    // as the JavaScript interpreter will always convert `\u0022` to `"`.321    this.parseError("\\u0022abc\\u0022", "Unicode-escaped double quote delimiters are not permitted");322    this.parseError('"ab'+"c'", "Strings must terminate with a double quote character");323    this.parses("", '""', "Strings may be empty");324    // Tests 15.12.1.1-g4-1 thru 15.12.1.1-g4-4.325    this.parseError('"\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007"', "Unescaped control characters in the range [U+0000, U+0007] are not permitted within strings");326    this.parseError('"\u0008\u0009\u000a\u000b\u000c\u000d\u000e\u000f"', "Unescaped control characters in the range [U+0008, U+000F] are not permitted within strings");327    this.parseError('"\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017"', "Unescaped control characters in the range [U+0010, U+0017] are not permitted within strings");328    this.parseError('"\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f"', "Unescaped control characters in the range [U+0018, U+001F] are not permitted within strings");329    // Tests 15.12.1.1-g5-1 thru 15.12.1.1-g5-3.330    this.parses("X", '"\\u0058"', "Unicode escape sequences are permitted within strings");331    this.parseError('"\\u005"', "Unicode escape sequences may not comprise fewer than four hexdigits");332    this.parseError('"\\u0X50"', "Unicode escape sequences may not contain non-hex characters");333    // Tests 15.12.1.1-g6-1 thru 15.12.1.1-g6-7.334    this.parses("/", '"\\/"', "Escaped solidus");335    this.parses("\\", '"\\\\"', "Escaped reverse solidus");336    this.parses("\b", '"\\b"', "Escaped backspace");337    this.parses("\f", '"\\f"', "Escaped form feed");338    this.parses("\n", '"\\n"', "Escaped line feed");339    this.parses("\r", '"\\r"', "Escaped carriage return");340    this.parses("\t", '"\\t"', "Escaped tab");341    // Section 15.12.3: `JSON.stringify()`.342    // ------------------------------------343    // Test 15.12.3-11-1 thru 5.12.3-11-15.344    this.serializes(void 0, void 0, "`JSON.stringify(undefined)` should return `undefined`");345    this.serializes('"replacement"', void 0, "The `JSON.stringify` callback function can be called on a top-level `undefined` value", function () {346      return "replacement";...generaterr.js
Source:generaterr.js  
1/* jshint expr: true */2var expect = require('chai').expect;3var generaterr = require('../index');4describe('generaterr', function() {5  it('should generate error constructors', function() {6    var errorConstructor = generaterr('ParseError');7    expect(errorConstructor).to.be.a('function');8  });9  it('should create instances of "Error"', function() {10    var ParseError = generaterr('ParseError');11    var err = new ParseError('');12    expect(err).to.be.an.instanceof(Error);13  });14  it('should allow errors to be generated without a message', function() {15    var ParseError = generaterr('ParseError');16    var err = new ParseError();17    expect(err.message).to.be.equal('');18  });19  it('should expose message', function() {20    var ParseError = generaterr('ParseError');21    var err = new ParseError('Could not parse file due to missing semicolons');22    expect(err.message).to.equal('Could not parse file due to missing semicolons');23  });24  it('should throw an error with message, name and stack trace', function(done) {25    var ParseError = generaterr('ParseError');26    try27    {28      throw new ParseError('Could not parse file due to missing semicolons');29    } catch(e) {30      expect(e.message).to.equal('Could not parse file due to missing semicolons');31      expect(e.name).to.equal('ParseError');32      expect(e.stack).to.exist;33      done();34    }35  });36  it('should throw an error without stack trace if turned off by options', function(done) {37    var ParseError = generaterr('ParseError', {}, { captureStackTrace : false });38    try39    {40      throw new ParseError('Could not parse file due to missing semicolons');41    } catch(e) {42      expect(e.stack).to.not.exist;43      done();44    }45  });46  it('should allow to pass options only', function(done) {47    var ParseError = generaterr('ParseError', null, { captureStackTrace : false });48    try49    {50      throw new ParseError('Could not parse file due to missing semicolons');51    } catch(e) {52      expect(e.stack).to.not.exist;53      done();54    }55  });56  it('should format messages with util.format', function(done) {57    var ParseError = generaterr('ParseError');58    try59    {60      throw new ParseError('Could not parse file "%s" due to missing semicolons at line %d:%d', 'input.js', 10, 12);61    } catch(e) {62      expect(e.message).to.equal('Could not parse file "input.js" due to missing semicolons at line 10:12');63      done();64    }65  });66  it('should last argument object to error instance', function() {67    var ParseError = generaterr('ParseError');68    var err = new ParseError('Could not parse file "%s" due to missing semicolons at line %d:%d', 'input.js', 10, 12, { status : 'FATAL' });69    expect(err.message).to.equal('Could not parse file "input.js" due to missing semicolons at line 10:12');70    expect(err.status).to.equal('FATAL');71  });72  it('should copy parameters passed to constructor generator functions to error instance', function() {73    var NotFoundError = generaterr('NotFoundError', { status : 404 });74    var notFoundError = new NotFoundError('Could find resource /api/random/numbers');75    expect(notFoundError.status).to.equal(404);76    expect(notFoundError.name).to.equal('NotFoundError');77  });78  it('should create an error with new if not invoked with "new" keyword', function() {79    var NotFoundError = generaterr('NotFoundError');80    var err = NotFoundError('Could find resource /api/random/numbers');81    expect(err).to.be.instanceof(NotFoundError);82    expect(err.message).to.equal('Could find resource /api/random/numbers');83  });84  it('should create an error with new if not invoked with "new" keyword with parameters', function() {85    var NotFoundError = generaterr('NotFoundError');86    var err = NotFoundError('Could find resource /api/random/numbers', { status : 'FATAL' });87    expect(err).to.be.instanceof(NotFoundError);88    expect(err.status).to.equal('FATAL');89    expect(err.message).to.equal('Could find resource /api/random/numbers');90  });91  it('should override error constructor properties', function() {92    var ExternalServiceError = generaterr('ExternalServiceError', { status : 500 });93    var url = 'http://localhost';94    var err = new ExternalServiceError('Communication with api api "%s" failed due to error', url, { status : 404 });95    expect(err.status).to.equal(404);96  });97  it('should inherit from passed error', function() {98    var SuperError = generaterr('ParentError');99    var InheritedError = generaterr('InheritedError', {}, { inherits : SuperError });100    var err = new InheritedError('Communication with api api "%s" failed due to error');101    expect(err).to.be.instanceof(SuperError);102  });...ParseError.js
Source:ParseError.js  
1var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");2Object.defineProperty(exports, "__esModule", {3  value: true4});5exports.default = void 0;6var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));7var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));8var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));9var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));10var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));11var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));12var _wrapNativeSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/wrapNativeSuper"));13function _createSuper(Derived) {14  var hasNativeReflectConstruct = _isNativeReflectConstruct();15  return function () {16    var Super = (0, _getPrototypeOf2.default)(Derived),17        result;18    if (hasNativeReflectConstruct) {19      var NewTarget = (0, _getPrototypeOf2.default)(this).constructor;20      result = Reflect.construct(Super, arguments, NewTarget);21    } else {22      result = Super.apply(this, arguments);23    }24    return (0, _possibleConstructorReturn2.default)(this, result);25  };26}27function _isNativeReflectConstruct() {28  if (typeof Reflect === "undefined" || !Reflect.construct) return false;29  if (Reflect.construct.sham) return false;30  if (typeof Proxy === "function") return true;31  try {32    Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));33    return true;34  } catch (e) {35    return false;36  }37}38var ParseError = function (_Error) {39  (0, _inherits2.default)(ParseError, _Error);40  var _super = _createSuper(ParseError);41  function ParseError(code, message) {42    var _this;43    (0, _classCallCheck2.default)(this, ParseError);44    _this = _super.call(this, message);45    _this.code = code;46    Object.defineProperty((0, _assertThisInitialized2.default)(_this), 'message', {47      enumerable: true,48      value: message49    });50    return _this;51  }52  (0, _createClass2.default)(ParseError, [{53    key: "toString",54    value: function () {55      return 'ParseError: ' + this.code + ' ' + this.message;56    }57  }]);58  return ParseError;59}((0, _wrapNativeSuper2.default)(Error));60ParseError.OTHER_CAUSE = -1;61ParseError.INTERNAL_SERVER_ERROR = 1;62ParseError.CONNECTION_FAILED = 100;63ParseError.OBJECT_NOT_FOUND = 101;64ParseError.INVALID_QUERY = 102;65ParseError.INVALID_CLASS_NAME = 103;66ParseError.MISSING_OBJECT_ID = 104;67ParseError.INVALID_KEY_NAME = 105;68ParseError.INVALID_POINTER = 106;69ParseError.INVALID_JSON = 107;70ParseError.COMMAND_UNAVAILABLE = 108;71ParseError.NOT_INITIALIZED = 109;72ParseError.INCORRECT_TYPE = 111;73ParseError.INVALID_CHANNEL_NAME = 112;74ParseError.PUSH_MISCONFIGURED = 115;75ParseError.OBJECT_TOO_LARGE = 116;76ParseError.OPERATION_FORBIDDEN = 119;77ParseError.CACHE_MISS = 120;78ParseError.INVALID_NESTED_KEY = 121;79ParseError.INVALID_FILE_NAME = 122;80ParseError.INVALID_ACL = 123;81ParseError.TIMEOUT = 124;82ParseError.INVALID_EMAIL_ADDRESS = 125;83ParseError.MISSING_CONTENT_TYPE = 126;84ParseError.MISSING_CONTENT_LENGTH = 127;85ParseError.INVALID_CONTENT_LENGTH = 128;86ParseError.FILE_TOO_LARGE = 129;87ParseError.FILE_SAVE_ERROR = 130;88ParseError.DUPLICATE_VALUE = 137;89ParseError.INVALID_ROLE_NAME = 139;90ParseError.EXCEEDED_QUOTA = 140;91ParseError.SCRIPT_FAILED = 141;92ParseError.VALIDATION_ERROR = 142;93ParseError.INVALID_IMAGE_DATA = 143;94ParseError.UNSAVED_FILE_ERROR = 151;95ParseError.INVALID_PUSH_TIME_ERROR = 152;96ParseError.FILE_DELETE_ERROR = 153;97ParseError.FILE_DELETE_UNNAMED_ERROR = 161;98ParseError.REQUEST_LIMIT_EXCEEDED = 155;99ParseError.DUPLICATE_REQUEST = 159;100ParseError.INVALID_EVENT_NAME = 160;101ParseError.INVALID_VALUE = 162;102ParseError.USERNAME_MISSING = 200;103ParseError.PASSWORD_MISSING = 201;104ParseError.USERNAME_TAKEN = 202;105ParseError.EMAIL_TAKEN = 203;106ParseError.EMAIL_MISSING = 204;107ParseError.EMAIL_NOT_FOUND = 205;108ParseError.SESSION_MISSING = 206;109ParseError.MUST_CREATE_USER_THROUGH_SIGNUP = 207;110ParseError.ACCOUNT_ALREADY_LINKED = 208;111ParseError.INVALID_SESSION_TOKEN = 209;112ParseError.MFA_ERROR = 210;113ParseError.MFA_TOKEN_REQUIRED = 211;114ParseError.LINKED_ID_MISSING = 250;115ParseError.INVALID_LINKED_SESSION = 251;116ParseError.UNSUPPORTED_SERVICE = 252;117ParseError.INVALID_SCHEMA_OPERATION = 255;118ParseError.AGGREGATE_ERROR = 600;119ParseError.FILE_READ_ERROR = 601;120ParseError.X_DOMAIN_REQUEST = 602;121var _default = ParseError;...parse-code-spec.js
Source:parse-code-spec.js  
1"use babel"2/*eslint-env jasmine */3import parseCode from '../lib/parse-code.js'4import fs from 'fs'5import path from 'path'6describe("makeCache.parseCode", function() {7    it("can parse every file in js-hyperclick", function() {8        const filenames = [9            './parse-code-spec.js',10            '../lib/js-hyperclick.js',11            '../lib/make-cache.js',12            '../lib/parse-code.js',13            '../lib/suggestions.js',14            '../.eslintrc.js'15        ]16        filenames.forEach(name => {17            const fullFilename = path.join(__dirname, name)18            const code = String(fs.readFileSync(fullFilename))19            const { parseError } = parseCode(code)20            expect(parseError && parseError.message).toBeUndefined(fullFilename)21        })22    })23    it("gathers the scopes for a file", function() {24        const { parseError, scopes: actual } = parseCode(`25        // 126        (function() {27            // 228            var noop = () => null // 329            if (noop) {30                // 431            }32            function foo() {33                // 534            }35        }())36        `)37        if (parseError) throw parseError38        expect(actual.length).toBe(5)39    })40    it("Gathers requires", function() {41        const { parseError, externalModules: actual } = parseCode(`42        const foo = require('./foo')43        const badRequire = require(foo.name)44        const { bar } = require('./bar')45        import someDefault, { named as renamed, notRenamed } from './other'46        function whatever() {47            const x = require('something')48        }49        `)50        if (parseError) throw parseError51        let id = 052        expect(actual[id].local).toBe('foo')53        expect(actual[id].module).toBe('./foo')54        expect(actual[id].imported).toBe('default')55        id++56        expect(actual[id].local).toBe('bar')57        expect(actual[id].module).toBe('./bar')58        expect(actual[id].imported).toBe('default')59        id++60        expect(actual[id].local).toBe('someDefault')61        expect(actual[id].module).toBe('./other')62        expect(actual[id].imported).toBe('default')63        id++64        expect(actual[id].local).toBe('renamed')65        expect(actual[id].module).toBe('./other')66        expect(actual[id].imported).toBe('named')67        id++68        expect(actual[id].local).toBe('notRenamed')69        expect(actual[id].module).toBe('./other')70        expect(actual[id].imported).toBe('notRenamed')71        id++72        expect(actual[id].local).toBe('x')73        expect(actual[id].module).toBe('something')74        expect(actual[id].imported).toBe('default')75    })76    it("Gathers exports", function() {77        const { parseError, exports: actual } = parseCode(`78        export default function Something() {}79        export { bar }80        export { whatever as baz}81        export const foo = 'foo'82        export function exportedFunction() {}83        `)84        if (parseError) throw parseError85        expect(actual.default).not.toBeUndefined()86        expect(actual.bar).not.toBeUndefined()87        expect(actual.whatever).toBeUndefined()88        expect(actual.baz).not.toBeUndefined()89        expect(actual.foo).not.toBeUndefined()90        expect(actual.exportedFunction).not.toBeUndefined()91    })92    it("Gathers module.exports", function() {93        const {parseError, exports: actual} = parseCode(`94        module.exports = {}95        `)96        if (parseError) throw parseError97        expect(actual.default).not.toBeUndefined()98    })99    it("Gathers paths from imports / requires", function() {100        const { parseError, paths: actual } = parseCode(`101        const foo = require('./foo')102        const badRequire = require(foo.name)103        const { bar } = require('./bar')104        import someDefault, { named as renamed, notRenamed } from './other'105        function whatever() {106            const x = require('something')107        }108        export * from './export-all'109        export { y } from './named-exports'110        export default from './base/Component.react'111        `)112        if (parseError) throw parseError113        expect(actual[0].module).toBe('./foo')114        expect(actual[1].module).toBe('./bar')115        expect(actual[2].module).toBe('./other')116        expect(actual[3].module).toBe('something')117        expect(actual[4].module).toBe('./export-all')118        expect(actual[5].module).toBe('./named-exports')119        expect(actual[6].module).toBe('./base/Component.react')120    })...4b7126c9078a81b89f4868d29d92595eeaec19ParseError.js
Source:4b7126c9078a81b89f4868d29d92595eeaec19ParseError.js  
1Object.defineProperty(exports, "__esModule", {2  value: true3});4var ParseError = function ParseError(code, message) {5  babelHelpers.classCallCheck(this, ParseError);6  this.code = code;7  this.message = message;8};9exports.default = ParseError;10ParseError.OTHER_CAUSE = -1;11ParseError.INTERNAL_SERVER_ERROR = 1;12ParseError.CONNECTION_FAILED = 100;13ParseError.OBJECT_NOT_FOUND = 101;14ParseError.INVALID_QUERY = 102;15ParseError.INVALID_CLASS_NAME = 103;16ParseError.MISSING_OBJECT_ID = 104;17ParseError.INVALID_KEY_NAME = 105;18ParseError.INVALID_POINTER = 106;19ParseError.INVALID_JSON = 107;20ParseError.COMMAND_UNAVAILABLE = 108;21ParseError.NOT_INITIALIZED = 109;22ParseError.INCORRECT_TYPE = 111;23ParseError.INVALID_CHANNEL_NAME = 112;24ParseError.PUSH_MISCONFIGURED = 115;25ParseError.OBJECT_TOO_LARGE = 116;26ParseError.OPERATION_FORBIDDEN = 119;27ParseError.CACHE_MISS = 120;28ParseError.INVALID_NESTED_KEY = 121;29ParseError.INVALID_FILE_NAME = 122;30ParseError.INVALID_ACL = 123;31ParseError.TIMEOUT = 124;32ParseError.INVALID_EMAIL_ADDRESS = 125;33ParseError.MISSING_CONTENT_TYPE = 126;34ParseError.MISSING_CONTENT_LENGTH = 127;35ParseError.INVALID_CONTENT_LENGTH = 128;36ParseError.FILE_TOO_LARGE = 129;37ParseError.FILE_SAVE_ERROR = 130;38ParseError.DUPLICATE_VALUE = 137;39ParseError.INVALID_ROLE_NAME = 139;40ParseError.EXCEEDED_QUOTA = 140;41ParseError.SCRIPT_FAILED = 141;42ParseError.VALIDATION_ERROR = 142;43ParseError.INVALID_IMAGE_DATA = 143;44ParseError.UNSAVED_FILE_ERROR = 151;45ParseError.INVALID_PUSH_TIME_ERROR = 152;46ParseError.FILE_DELETE_ERROR = 153;47ParseError.REQUEST_LIMIT_EXCEEDED = 155;48ParseError.INVALID_EVENT_NAME = 160;49ParseError.USERNAME_MISSING = 200;50ParseError.PASSWORD_MISSING = 201;51ParseError.USERNAME_TAKEN = 202;52ParseError.EMAIL_TAKEN = 203;53ParseError.EMAIL_MISSING = 204;54ParseError.EMAIL_NOT_FOUND = 205;55ParseError.SESSION_MISSING = 206;56ParseError.MUST_CREATE_USER_THROUGH_SIGNUP = 207;57ParseError.ACCOUNT_ALREADY_LINKED = 208;58ParseError.INVALID_SESSION_TOKEN = 209;59ParseError.LINKED_ID_MISSING = 250;60ParseError.INVALID_LINKED_SESSION = 251;61ParseError.UNSUPPORTED_SERVICE = 252;62ParseError.AGGREGATE_ERROR = 600;63ParseError.FILE_READ_ERROR = 601;...syntaxError.js
Source:syntaxError.js  
...28  }29  return ParseError;30}(SyntaxError));31exports.ParseError = ParseError;32function parseError(message, begin, end) {33  var e = new ParseError(message);34  if (Array.isArray(begin)) {35    e.begin = {36      row: begin[0] - 1,37      column: begin[1]38    };39  }40  if (Array.isArray(end)) {41    e.end = {42      row: end[0] - 1,43      column: end[1]44    };45  }46  return e;...parse-error.test.js
Source:parse-error.test.js  
1'use strict'2const { ParseError } = require('../../lib/sax')3describe('ParseError', () => {4	it('should have name ParseError', () => {5		expect(new ParseError('').name).toBe('ParseError')6	})7	it('should be an instance of Error', () => {8		expect(new ParseError('') instanceof Error).toBe(true)9	})10	it('should be an instance of ParseError', () => {11		expect(new ParseError('') instanceof ParseError).toBe(true)12	})13	it('should store first argument as message', () => {14		const error = new ParseError('FROM TEST')15		expect(error.message).toBe('FROM TEST')16	})17	it('should store second argument as locator', () => {18		const locator = {}19		const error = new ParseError('', locator)20		expect(error.locator).toBe(locator)21	})22	it('should have correct StackTrace', () => {23		const error = new ParseError('MESSAGE')24		const stack = error.stack && error.stack.split(/[\n\r]+/)25		expect(stack && stack.length).toBeGreaterThan(1)26		expect(stack[0]).toBe('ParseError: MESSAGE')27		expect(stack[1]).toContain(__filename)28	})29	it('Error should not be instanceof ParseError', () => {30		expect(new Error() instanceof ParseError).toBe(false)31	})...errors.js
Source:errors.js  
1/*!2 * Stylus - errors3 * Copyright (c) Automattic <developer.wordpress.com>4 * MIT Licensed5 */6/**7 * Expose constructors.8 */9exports.ParseError = ParseError;10exports.SyntaxError = SyntaxError;11/**12 * Inherit from `Error.prototype`.13 */14SyntaxError.prototype.__proto__ = Error.prototype;15/**16 * Initialize a new `ParseError` with the given `msg`.17 *18 * @param {String} msg19 * @api private20 */21function ParseError(msg) {22  this.name = 'ParseError';23  this.message = msg;24  Error.captureStackTrace(this, ParseError);25}26/**27 * Inherit from `Error.prototype`.28 */29ParseError.prototype.__proto__ = Error.prototype;30/**31 * Initialize a new `SyntaxError` with the given `msg`.32 *33 * @param {String} msg34 * @api private35 */36function SyntaxError(msg) {37  this.name = 'SyntaxError';38  this.message = msg;39  Error.captureStackTrace(this, ParseError);40}41/**42 * Inherit from `Error.prototype`.43 */...Using AI Code Generation
1const { parseError } = require('playwright/lib/utils/stackTrace');2const { chromium } = require('playwright');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.screenshot({ path: 'example.png' });8  await browser.close();9})();10const { parseError } = require('playwright/lib/utils/stackTrace');11const { chromium } = require('playwright');12(async () => {13  const browser = await chromium.launch();14  const context = await browser.newContext();15  const page = await context.newPage();16  await page.screenshot({ path: 'example.png' });17  await browser.close();18})();19    at CDPSession.send (C:\Users\hp\Documents\GitHub\playwrightTest\node_modules\playwright\lib\cdp.js:69:19)20    at ExecutionContext._evaluateInternal (C:\Users\hp\Documents\GitHub\playwrightTest\node_modules\playwright\lib\executionContext.js:222:50)21    at ExecutionContext.evaluateHandle (C:\Users\hp\Documents\GitHub\playwrightTest\node_modules\playwright\lib\executionContext.js:109:17)22    at Page._pageBindings.get.e (C:\Users\hp\Documents\GitHub\playwrightTest\node_modules\playwright\lib\page.js:1085:63)23    at Page._onBindingCalled (C:\Users\hp\Documents\GitHub\playwrightTest\node_modules\playwright\lib\page.js:1082:14)24    at CDPSession.Page.client.on.event (C:\Users\hp\Documents\GitHub\playwrightTest\node_modules\playwright\lib\page.js:87:57)25    at CDPSession.emit (events.js:315:20)26    at CDPSession._onMessage (C:\Users\hp\Documents\GitHub\playwrightTest\node_modules\playwright\lib\cdp.js:96Using AI Code Generation
1const { parseError } = require('playwright-core/lib/utils/stackTrace');2const { PlaywrightError } = require('playwright-core/lib/utils/errors');3const { TimeoutError } = require('playwright-core/lib/errors');4const error = new TimeoutError('Timeout', 30000);5const playwrightError = new PlaywrightError('Error', error);6console.log(parseError(playwrightError));Using AI Code Generation
1const { parseError } = require('playwright-core/lib/utils/stackTrace');2const { TimeoutError } = require('playwright-core/lib/errors');3const error = new TimeoutError('Timeout');4console.log(parseError(error));5{6    '    at TimeoutError (/Users/username/Documents/playwright/test.js:5:9)\n' +7    '    at Timeout._onTimeout (/Users/username/Documents/playwright/test.js:7:13)\n' +8    '    at listOnTimeout (internal/timers.js:554:17)\n' +9    '    at processTimers (internal/timers.js:497:7)'10}Using AI Code Generation
1const { parseError } = require('playwright-core/lib/utils/utils');2const { TimeoutError } = require('playwright-core/lib/errors');3const error = new TimeoutError('Timeout');4const parsedError = parseError(error);5console.log(parsedError);6{ message: 'Timeout',7at TimeoutError.ExtendableBuiltin (/Users/username/playwright-test/node_modules/playwright-core/lib/utils/stackTrace.js:20:28)8at TimeoutError.Error (/Users/username/playwright-test/node_modules/playwright-core/lib/utils/stackTrace.js:12:47)9at new TimeoutError (/Users/username/playwright-test/node_modules/playwright-core/lib/errors.js:12:28)10at Timeout._onTimeout (/Users/username/playwright-test/test.js:5:19)11at listOnTimeout (internal/timers.js:549:17)12at processTimers (internal/timers.js:492:7)',13  isPlaywrightError: true }Using AI Code Generation
1const { parseError } = require('playwright/lib/utils/stackTrace');2const { InternalError } = require('playwright/lib/utils/error');3const internalError = new InternalError('message', 'stack');4const parsedError = parseError(internalError);5console.log(parsedError);6const { parseError } = require('playwright/lib/utils/stackTrace');7const { Error } = require('playwright/lib/utils/error');8const error = new Error('message', 'stack');9const parsedError = parseError(error);10console.log(parsedError);11const { parseError } = require('playwright/lib/utils/stackTrace');12const { InternalError } = require('playwright/lib/utils/error');13const internalError = new InternalError('message', 'stack');14const parsedError = parseError(internalError);15console.log(parsedError);16const { parseError } = require('playwright/lib/utils/stackTrace');17const { Error } = require('playwright/lib/utils/error');18const error = new Error('message', 'stack');19const parsedError = parseError(error);20console.log(parsedError);21if (error.stack && !Array.isArray(error.stack))22  error.stack = error.stack.split('23');Using AI Code Generation
1const { parseError } = require('playwright/lib/utils/stackTrace');2const { expect } = require('chai');3describe('test', () => {4  it('should throw error', () => {5    try {6      throw new Error('some error');7    } catch (error) {8      const parsedError = parseError(error);9      expect(parsedError.message).to.equal('some error');10    }11  });12});13{14  "dependencies": {15  },16  "devDependencies": {17  }18}19    at Context.<anonymous> (test.js:9:15)20    at processImmediate (internal/timers.js:461:21)21    at Context.<anonymous> (test.js:9:15)22    at processImmediate (internal/timers.js:461:21)23    at Object.parseError (node_modules/playwright/lib/utils/stackTrace.js:37:12)24    at Context.<anonymous> (test.js:11:31)25const parsedError = parseError(error);26const parsedError = parseError(error);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.
Get 100 minutes of automation test minutes FREE!!
