Best JavaScript code snippet using chai
assertions.js
Source:assertions.js  
1/*!2 * chai3 * http://chaijs.com4 * Copyright(c) 2011-2012 Jake Luer <jake@alogicalparadox.com>5 * MIT Licensed6 */7module.exports = function (chai, _) {8  var Assertion = chai.Assertion9    , toString = Object.prototype.toString10    , flag = _.flag;11  /**12   * ### Language Chains13   *14   * The following are provide as chainable getters to15   * improve the readability of your assertions. They16   * do not provide an testing capability unless they17   * have been overwritten by a plugin.18   *19   * **Chains**20   *21   * - to22   * - be23   * - been24   * - is25   * - that26   * - and27   * - have28   * - with29   *30   * @name language chains31   * @api public32   */33  [ 'to', 'be', 'been'34  , 'is', 'and', 'have'35  , 'with', 'that' ].forEach(function (chain) {36    Assertion.addProperty(chain, function () {37      return this;38    });39  });40  /**41   * ### .not42   *43   * Negates any of assertions following in the chain.44   *45   *     expect(foo).to.not.equal('bar');46   *     expect(goodFn).to.not.throw(Error);47   *     expect({ foo: 'baz' }).to.have.property('foo')48   *       .and.not.equal('bar');49   *50   * @name not51   * @api public52   */53  Assertion.addProperty('not', function () {54    flag(this, 'negate', true);55  });56  /**57   * ### .deep58   *59   * Sets the `deep` flag, later used by the `equal` and60   * `property` assertions.61   *62   *     expect(foo).to.deep.equal({ bar: 'baz' });63   *     expect({ foo: { bar: { baz: 'quux' } } })64   *       .to.have.deep.property('foo.bar.baz', 'quux');65   *66   * @name deep67   * @api public68   */69  Assertion.addProperty('deep', function () {70    flag(this, 'deep', true);71  });72  /**73   * ### .a(type)74   *75   * The `a` and `an` assertions are aliases that can be76   * used either as language chains or to assert a value's77   * type (as revealed by `Object.prototype.toString`).78   *79   *     // typeof80   *     expect('test').to.be.a('string');81   *     expect({ foo: 'bar' }).to.be.an('object');82   *     expect(null).to.be.a('null');83   *     expect(undefined).to.be.an('undefined');84   *85   *     // language chain86   *     expect(foo).to.be.an.instanceof(Foo);87   *88   * @name a89   * @alias an90   * @param {String} type91   * @api public92   */93  function an(type) {94    var obj = flag(this, 'object')95      , klassStart = type.charAt(0).toUpperCase()96      , klass = klassStart + type.slice(1)97      , article = ~[ 'A', 'E', 'I', 'O', 'U' ].indexOf(klassStart) ? 'an ' : 'a ';98    this.assert(99        '[object ' + klass + ']' === toString.call(obj)100      , 'expected #{this} to be ' + article + type101      , 'expected #{this} not to be ' + article + type102    );103  }104  Assertion.addChainableMethod('an', an);105  Assertion.addChainableMethod('a', an);106  /**107   * ### .include(value)108   *109   * The `include` and `contain` assertions can be used as either property110   * based language chains or as methods to assert the inclusion of an object111   * in an array or a substring in a string. When used as language chains,112   * they toggle the `contain` flag for the `keys` assertion.113   *114   *     expect([1,2,3]).to.include(2);115   *     expect('foobar').to.contain('foo');116   *     expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo');117   *118   * @name include119   * @alias contain120   * @param {Object|String|Number} obj121   * @api public122   */123  function includeChainingBehavior () {124    flag(this, 'contains', true);125  }126  function include (val) {127    var obj = flag(this, 'object')128    this.assert(129        ~obj.indexOf(val)130      , 'expected #{this} to include ' + _.inspect(val)131      , 'expected #{this} to not include ' + _.inspect(val));132  }133  Assertion.addChainableMethod('include', include, includeChainingBehavior);134  Assertion.addChainableMethod('contain', include, includeChainingBehavior);135  /**136   * ### .ok137   *138   * Asserts that the target is truthy.139   *140   *     expect('everthing').to.be.ok;141   *     expect(1).to.be.ok;142   *     expect(false).to.not.be.ok;143   *     expect(undefined).to.not.be.ok;144   *     expect(null).to.not.be.ok;145   *146   * @name ok147   * @api public148   */149  Assertion.addProperty('ok', function () {150    this.assert(151        flag(this, 'object')152      , 'expected #{this} to be truthy'153      , 'expected #{this} to be falsy');154  });155  /**156   * ### .true157   *158   * Asserts that the target is `true`.159   *160   *     expect(true).to.be.true;161   *     expect(1).to.not.be.true;162   *163   * @name true164   * @api public165   */166  Assertion.addProperty('true', function () {167    this.assert(168        true === flag(this, 'object')169      , 'expected #{this} to be true'170      , 'expected #{this} to be false'171      , this.negate ? false : true172    );173  });174  /**175   * ### .false176   *177   * Asserts that the target is `false`.178   *179   *     expect(false).to.be.false;180   *     expect(0).to.not.be.false;181   *182   * @name false183   * @api public184   */185  Assertion.addProperty('false', function () {186    this.assert(187        false === flag(this, 'object')188      , 'expected #{this} to be false'189      , 'expected #{this} to be true'190      , this.negate ? true : false191    );192  });193  /**194   * ### .null195   *196   * Asserts that the target is `null`.197   *198   *     expect(null).to.be.null;199   *     expect(undefined).not.to.be.null;200   *201   * @name null202   * @api public203   */204  Assertion.addProperty('null', function () {205    this.assert(206        null === flag(this, 'object')207      , 'expected #{this} to be null'208      , 'expected #{this} not to be null'209    );210  });211  /**212   * ### .undefined213   *214   * Asserts that the target is `undefined`.215   *216   *      expect(undefined).to.be.undefined;217   *      expect(null).to.not.be.undefined;218   *219   * @name undefined220   * @api public221   */222  Assertion.addProperty('undefined', function () {223    this.assert(224        undefined === flag(this, 'object')225      , 'expected #{this} to be undefined'226      , 'expected #{this} not to be undefined'227    );228  });229  /**230   * ### .exist231   *232   * Asserts that the target is neither `null` nor `undefined`.233   *234   *     var foo = 'hi'235   *       , bar = null236   *       , baz;237   *238   *     expect(foo).to.exist;239   *     expect(bar).to.not.exist;240   *     expect(baz).to.not.exist;241   *242   * @name exist243   * @api public244   */245  Assertion.addProperty('exist', function () {246    this.assert(247        null != flag(this, 'object')248      , 'expected #{this} to exist'249      , 'expected #{this} to not exist'250    );251  });252  /**253   * ### .empty254   *255   * Asserts that the target's length is `0`. For arrays, it checks256   * the `length` property. For objects, it gets the count of257   * enumerable keys.258   *259   *     expect([]).to.be.empty;260   *     expect('').to.be.empty;261   *     expect({}).to.be.empty;262   *263   * @name empty264   * @api public265   */266  Assertion.addProperty('empty', function () {267    var obj = flag(this, 'object')268      , expected = obj;269    if (Array.isArray(obj) || 'string' === typeof object) {270      expected = obj.length;271    } else if (typeof obj === 'object') {272      expected = Object.keys(obj).length;273    }274    this.assert(275        !expected276      , 'expected #{this} to be empty'277      , 'expected #{this} not to be empty'278    );279  });280  /**281   * ### .arguments282   *283   * Asserts that the target is an arguments object.284   *285   *     function test () {286   *       expect(arguments).to.be.arguments;287   *     }288   *289   * @name arguments290   * @alias Arguments291   * @api public292   */293  function checkArguments () {294    var obj = flag(this, 'object')295      , type = Object.prototype.toString.call(obj);296    this.assert(297        '[object Arguments]' === type298      , 'expected #{this} to be arguments but got ' + type299      , 'expected #{this} to not be arguments'300    );301  }302  Assertion.addProperty('arguments', checkArguments);303  Assertion.addProperty('Arguments', checkArguments);304  /**305   * ### .equal(value)306   *307   * Asserts that the target is strictly equal (`===`) to `value`.308   * Alternately, if the `deep` flag is set, asserts that309   * the target is deeply equal to `value`.310   *311   *     expect('hello').to.equal('hello');312   *     expect(42).to.equal(42);313   *     expect(1).to.not.equal(true);314   *     expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' });315   *     expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' });316   *317   * @name equal318   * @alias eq319   * @alias deep.equal320   * @param {Mixed} value321   * @api public322   */323  function assertEqual (val) {324    var obj = flag(this, 'object');325    if (flag(this, 'deep')) {326      return this.eql(val);327    } else {328      this.assert(329          val === obj330        , 'expected #{this} to equal #{exp}'331        , 'expected #{this} to not equal #{exp}'332        , val333      );334    }335  }336  Assertion.addMethod('equal', assertEqual);337  Assertion.addMethod('eq', assertEqual);338  /**339   * ### .eql(value)340   *341   * Asserts that the target is deeply equal to `value`.342   *343   *     expect({ foo: 'bar' }).to.eql({ foo: 'bar' });344   *     expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]);345   *346   * @name eql347   * @param {Mixed} value348   * @api public349   */350  Assertion.addMethod('eql', function (obj) {351    this.assert(352        _.eql(obj, flag(this, 'object'))353      , 'expected #{this} to deeply equal #{exp}'354      , 'expected #{this} to not deeply equal #{exp}'355      , obj356    );357  });358  /**359   * ### .above(value)360   *361   * Asserts that the target is greater than `value`.362   *363   *     expect(10).to.be.above(5);364   *365   * Can also be used in conjunction with `length` to366   * assert a minimum length. The benefit being a367   * more informative error message than if the length368   * was supplied directly.369   *370   *     expect('foo').to.have.length.above(2);371   *     expect([ 1, 2, 3 ]).to.have.length.above(2);372   *373   * @name above374   * @alias gt375   * @alias greaterThan376   * @param {Number} value377   * @api public378   */379  function assertAbove (n) {380    var obj = flag(this, 'object');381    if (flag(this, 'doLength')) {382      new Assertion(obj).to.have.property('length');383      var len = obj.length;384      this.assert(385          len > n386        , 'expected #{this} to have a length above #{exp} but got #{act}'387        , 'expected #{this} to not have a length above #{exp}'388        , n389        , len390      );391    } else {392      this.assert(393          obj > n394        , 'expected #{this} to be above ' + n395        , 'expected #{this} to be below ' + n396      );397    }398  }399  Assertion.addMethod('above', assertAbove);400  Assertion.addMethod('gt', assertAbove);401  Assertion.addMethod('greaterThan', assertAbove);402  /**403   * ### .below(value)404   *405   * Asserts that the target is less than `value`.406   *407   *     expect(5).to.be.below(10);408   *409   * Can also be used in conjunction with `length` to410   * assert a maximum length. The benefit being a411   * more informative error message than if the length412   * was supplied directly.413   *414   *     expect('foo').to.have.length.below(4);415   *     expect([ 1, 2, 3 ]).to.have.length.below(4);416   *417   * @name below418   * @alias lt419   * @alias lessThan420   * @param {Number} value421   * @api public422   */423  function assertBelow (n) {424    var obj = flag(this, 'object');425    if (flag(this, 'doLength')) {426      new Assertion(obj).to.have.property('length');427      var len = obj.length;428      this.assert(429          len < n430        , 'expected #{this} to have a length below #{exp} but got #{act}'431        , 'expected #{this} to not have a length below #{exp}'432        , n433        , len434      );435    } else {436      this.assert(437          obj < n438        , 'expected #{this} to be below ' + n439        , 'expected #{this} to be above ' + n440      );441    }442  }443  Assertion.addMethod('below', assertBelow);444  Assertion.addMethod('lt', assertBelow);445  Assertion.addMethod('lessThan', assertBelow);446  /**447   * ### .within(start, finish)448   *449   * Asserts that the target is within a range.450   *451   *     expect(7).to.be.within(5,10);452   *453   * Can also be used in conjunction with `length` to454   * assert a length range. The benefit being a455   * more informative error message than if the length456   * was supplied directly.457   *458   *     expect('foo').to.have.length.within(2,4);459   *     expect([ 1, 2, 3 ]).to.have.length.within(2,4);460   *461   * @name within462   * @param {Number} start lowerbound inclusive463   * @param {Number} finish upperbound inclusive464   * @api public465   */466  Assertion.addMethod('within', function (start, finish) {467    var obj = flag(this, 'object')468      , range = start + '..' + finish;469    if (flag(this, 'doLength')) {470      new Assertion(obj).to.have.property('length');471      var len = obj.length;472      this.assert(473          len >= start && len <= finish474        , 'expected #{this} to have a length within ' + range475        , 'expected #{this} to not have a length within ' + range476      );477    } else {478      this.assert(479          obj >= start && obj <= finish480        , 'expected #{this} to be within ' + range481        , 'expected #{this} to not be within ' + range482      );483    }484  });485  /**486   * ### .instanceof(constructor)487   *488   * Asserts that the target is an instance of `constructor`.489   *490   *     var Tea = function (name) { this.name = name; }491   *       , Chai = new Tea('chai');492   *493   *     expect(Chai).to.be.an.instanceof(Tea);494   *     expect([ 1, 2, 3 ]).to.be.instanceof(Array);495   *496   * @name instanceof497   * @param {Constructor} constructor498   * @alias instanceOf499   * @api public500   */501  function assertInstanceOf (constructor) {502    var name = _.getName(constructor);503    this.assert(504        flag(this, 'object') instanceof constructor505      , 'expected #{this} to be an instance of ' + name506      , 'expected #{this} to not be an instance of ' + name507    );508  };509  Assertion.addMethod('instanceof', assertInstanceOf);510  Assertion.addMethod('instanceOf', assertInstanceOf);511  /**512   * ### .property(name, [value])513   *514   * Asserts that the target has a property `name`, optionally asserting that515   * the value of that property is strictly equal to  `value`.516   * If the `deep` flag is set, you can use dot- and bracket-notation for deep517   * references into objects and arrays.518   *519   *     // simple referencing520   *     var obj = { foo: 'bar' };521   *     expect(obj).to.have.property('foo');522   *     expect(obj).to.have.property('foo', 'bar');523   *524   *     // deep referencing525   *     var deepObj = {526   *         green: { tea: 'matcha' }527   *       , teas: [ 'chai', 'matcha', { tea: 'konacha' } ]528   *     };529   *     expect(deepObj).to.have.deep.property('green.tea', 'matcha');530   *     expect(deepObj).to.have.deep.property('teas[1]', 'matcha');531   *     expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha');532   *533   * You can also use an array as the starting point of a `deep.property`534   * assertion, or traverse nested arrays.535   *536   *     var arr = [537   *         [ 'chai', 'matcha', 'konacha' ]538   *       , [ { tea: 'chai' }539   *         , { tea: 'matcha' }540   *         , { tea: 'konacha' } ]541   *     ];542   *543   *     expect(arr).to.have.deep.property('[0][1]', 'matcha');544   *     expect(arr).to.have.deep.property('[1][2].tea', 'konacha');545   *546   * Furthermore, `property` changes the subject of the assertion547   * to be the value of that property from the original object. This548   * permits for further chainable assertions on that property.549   *550   *     expect(obj).to.have.property('foo')551   *       .that.is.a('string');552   *     expect(deepObj).to.have.property('green')553   *       .that.is.an('object')554   *       .that.deep.equals({ tea: 'matcha' });555   *     expect(deepObj).to.have.property('teas')556   *       .that.is.an('array')557   *       .with.deep.property('[2]')558   *         .that.deep.equals({ tea: 'konacha' });559   *560   * @name property561   * @alias deep.property562   * @param {String} name563   * @param {Mixed} value (optional)564   * @returns value of property for chaining565   * @api public566   */567  Assertion.addMethod('property', function (name, val) {568    var obj = flag(this, 'object')569      , value = flag(this, 'deep') ? _.getPathValue(name, obj) : obj[name]570      , descriptor = flag(this, 'deep') ? 'deep property ' : 'property '571      , negate = flag(this, 'negate');572    if (negate && undefined !== val) {573      if (undefined === value) {574        throw new Error(_.inspect(obj) + ' has no ' + descriptor + _.inspect(name));575      }576    } else {577      this.assert(578          undefined !== value579        , 'expected #{this} to have a ' + descriptor + _.inspect(name)580        , 'expected #{this} to not have ' + descriptor + _.inspect(name));581    }582    if (undefined !== val) {583      this.assert(584          val === value585        , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}'586        , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}'587        , val588        , value589      );590    }591    flag(this, 'object', value);592  });593  /**594   * ### .ownProperty(name)595   *596   * Asserts that the target has an own property `name`.597   *598   *     expect('test').to.have.ownProperty('length');599   *600   * @name ownProperty601   * @alias haveOwnProperty602   * @param {String} name603   * @api public604   */605  function assertOwnProperty (name) {606    var obj = flag(this, 'object');607    this.assert(608        obj.hasOwnProperty(name)609      , 'expected #{this} to have own property ' + _.inspect(name)610      , 'expected #{this} to not have own property ' + _.inspect(name)611    );612  }613  Assertion.addMethod('ownProperty', assertOwnProperty);614  Assertion.addMethod('haveOwnProperty', assertOwnProperty);615  /**616   * ### .length(value)617   *618   * Asserts that the target's `length` property has619   * the expected value.620   *621   *     expect([ 1, 2, 3]).to.have.length(3);622   *     expect('foobar').to.have.length(6);623   *624   * Can also be used as a chain precursor to a value625   * comparison for the length property.626   *627   *     expect('foo').to.have.length.above(2);628   *     expect([ 1, 2, 3 ]).to.have.length.above(2);629   *     expect('foo').to.have.length.below(4);630   *     expect([ 1, 2, 3 ]).to.have.length.below(4);631   *     expect('foo').to.have.length.within(2,4);632   *     expect([ 1, 2, 3 ]).to.have.length.within(2,4);633   *634   * @name length635   * @alias lengthOf636   * @param {Number} length637   * @api public638   */639  function assertLengthChain () {640    flag(this, 'doLength', true);641  }642  function assertLength (n) {643    var obj = flag(this, 'object');644    new Assertion(obj).to.have.property('length');645    var len = obj.length;646    this.assert(647        len == n648      , 'expected #{this} to have a length of #{exp} but got #{act}'649      , 'expected #{this} to not have a length of #{act}'650      , n651      , len652    );653  }654  Assertion.addChainableMethod('length', assertLength, assertLengthChain);655  Assertion.addMethod('lengthOf', assertLength, assertLengthChain);656  /**657   * ### .match(regexp)658   *659   * Asserts that the target matches a regular expression.660   *661   *     expect('foobar').to.match(/^foo/);662   *663   * @name match664   * @param {RegExp} RegularExpression665   * @api public666   */667  Assertion.addMethod('match', function (re) {668    var obj = flag(this, 'object');669    this.assert(670        re.exec(obj)671      , 'expected #{this} to match ' + re672      , 'expected #{this} not to match ' + re673    );674  });675  /**676   * ### .string(string)677   *678   * Asserts that the string target contains another string.679   *680   *     expect('foobar').to.have.string('bar');681   *682   * @name string683   * @param {String} string684   * @api public685   */686  Assertion.addMethod('string', function (str) {687    var obj = flag(this, 'object');688    new Assertion(obj).is.a('string');689    this.assert(690        ~obj.indexOf(str)691      , 'expected #{this} to contain ' + _.inspect(str)692      , 'expected #{this} to not contain ' + _.inspect(str)693    );694  });695  /**696   * ### .keys(key1, [key2], [...])697   *698   * Asserts that the target has exactly the given keys, or699   * asserts the inclusion of some keys when using the700   * `include` or `contain` modifiers.701   *702   *     expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']);703   *     expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar');704   *705   * @name keys706   * @alias key707   * @param {String...|Array} keys708   * @api public709   */710  function assertKeys (keys) {711    var obj = flag(this, 'object')712      , str713      , ok = true;714    keys = keys instanceof Array715      ? keys716      : Array.prototype.slice.call(arguments);717    if (!keys.length) throw new Error('keys required');718    var actual = Object.keys(obj)719      , len = keys.length;720    // Inclusion721    ok = keys.every(function(key){722      return ~actual.indexOf(key);723    });724    // Strict725    if (!flag(this, 'negate') && !flag(this, 'contains')) {726      ok = ok && keys.length == actual.length;727    }728    // Key string729    if (len > 1) {730      keys = keys.map(function(key){731        return _.inspect(key);732      });733      var last = keys.pop();734      str = keys.join(', ') + ', and ' + last;735    } else {736      str = _.inspect(keys[0]);737    }738    // Form739    str = (len > 1 ? 'keys ' : 'key ') + str;740    // Have / include741    str = (flag(this, 'contains') ? 'contain ' : 'have ') + str;742    // Assertion743    this.assert(744        ok745      , 'expected #{this} to ' + str746      , 'expected #{this} to not ' + str747    );748  }749  Assertion.addMethod('keys', assertKeys);750  Assertion.addMethod('key', assertKeys);751  /**752   * ### .throw(constructor)753   *754   * Asserts that the function target will throw a specific error, or specific type of error755   * (as determined using `instanceof`), optionally with a RegExp or string inclusion test756   * for the error's message.757   *758   *     var err = new ReferenceError('This is a bad function.');759   *     var fn = function () { throw err; }760   *     expect(fn).to.throw(ReferenceError);761   *     expect(fn).to.throw(Error);762   *     expect(fn).to.throw(/bad function/);763   *     expect(fn).to.not.throw('good function');764   *     expect(fn).to.throw(ReferenceError, /bad function/);765   *     expect(fn).to.throw(err);766   *     expect(fn).to.not.throw(new RangeError('Out of range.'));767   *768   * Please note that when a throw expectation is negated, it will check each769   * parameter independently, starting with error constructor type. The appropriate way770   * to check for the existence of a type of error but for a message that does not match771   * is to use `and`.772   *773   *     expect(fn).to.throw(ReferenceError)774   *        .and.not.throw(/good function/);775   *776   * @name throw777   * @alias throws778   * @alias Throw779   * @param {ErrorConstructor} constructor780   * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types781   * @api public782   */783  function assertThrows (constructor, msg) {784    var obj = flag(this, 'object');785    new Assertion(obj).is.a('function');786    var thrown = false787      , desiredError = null788      , name = null;789    if (arguments.length === 0) {790      msg = null;791      constructor = null;792    } else if (constructor && (constructor instanceof RegExp || 'string' === typeof constructor)) {793      msg = constructor;794      constructor = null;795    } else if (constructor && constructor instanceof Error) {796      desiredError = constructor;797      constructor = null;798      msg = null;799    } else if (typeof constructor === 'function') {800      name = (new constructor()).name;801    } else {802      constructor = null;803    }804    try {805      obj();806    } catch (err) {807      // first, check desired error808      if (desiredError) {809        this.assert(810            err === desiredError811          , 'expected #{this} to throw ' + _.inspect(desiredError) + ' but ' + _.inspect(err) + ' was thrown'812          , 'expected #{this} to not throw ' + _.inspect(desiredError)813        );814        return this;815      }816      // next, check constructor817      if (constructor) {818        this.assert(819            err instanceof constructor820          , 'expected #{this} to throw ' + name + ' but a ' + err.name + ' was thrown'821          , 'expected #{this} to not throw ' + name );822        if (!msg) return this;823      }824      // next, check message825      if (err.message && msg && msg instanceof RegExp) {826        this.assert(827            msg.exec(err.message)828          , 'expected #{this} to throw error matching ' + msg + ' but got ' + _.inspect(err.message)829          , 'expected #{this} to throw error not matching ' + msg830        );831        return this;832      } else if (err.message && msg && 'string' === typeof msg) {833        this.assert(834            ~err.message.indexOf(msg)835          , 'expected #{this} to throw error including #{exp} but got #{act}'836          , 'expected #{this} to throw error not including #{act}'837          , msg838          , err.message839        );840        return this;841      } else {842        thrown = true;843      }844    }845    var expectedThrown = name ? name : desiredError ? _.inspect(desiredError) : 'an error';846    this.assert(847        thrown === true848      , 'expected #{this} to throw ' + expectedThrown849      , 'expected #{this} to not throw ' + expectedThrown850    );851  };852  Assertion.addMethod('throw', assertThrows);853  Assertion.addMethod('throws', assertThrows);854  Assertion.addMethod('Throw', assertThrows);855  /**856   * ### .respondTo(method)857   *858   * Asserts that the object or class target will respond to a method.859   *860   *     Klass.prototype.bar = function(){};861   *     expect(Klass).to.respondTo('bar');862   *     expect(obj).to.respondTo('bar');863   *864   * To check if a constructor will respond to a static function,865   * set the `itself` flag.866   *867   *    Klass.baz = function(){};868   *    expect(Klass).itself.to.respondTo('baz');869   *870   * @name respondTo871   * @param {String} method872   * @api public873   */874  Assertion.addMethod('respondTo', function (method) {875    var obj = flag(this, 'object')876      , itself = flag(this, 'itself')877      , context = ('function' === typeof obj && !itself)878        ? obj.prototype[method]879        : obj[method];880    this.assert(881        'function' === typeof context882      , 'expected #{this} to respond to ' + _.inspect(method)883      , 'expected #{this} to not respond to ' + _.inspect(method)884    );885  });886  /**887   * ### .itself888   *889   * Sets the `itself` flag, later used by the `respondTo` assertion.890   *891   *    function Foo() {}892   *    Foo.bar = function() {}893   *    Foo.prototype.baz = function() {}894   *895   *    expect(Foo).itself.to.respondTo('bar');896   *    expect(Foo).itself.not.to.respondTo('baz');897   *898   * @name itself899   * @api public900   */901  Assertion.addProperty('itself', function () {902    flag(this, 'itself', true);903  });904  /**905   * ### .satisfy(method)906   *907   * Asserts that the target passes a given truth test.908   *909   *     expect(1).to.satisfy(function(num) { return num > 0; });910   *911   * @name satisfy912   * @param {Function} matcher913   * @api public914   */915  Assertion.addMethod('satisfy', function (matcher) {916    var obj = flag(this, 'object');917    this.assert(918        matcher(obj)919      , 'expected #{this} to satisfy ' + _.inspect(matcher)920      , 'expected #{this} to not satisfy' + _.inspect(matcher)921      , this.negate ? false : true922      , matcher(obj)923    );924  });925  /**926   * ### .closeTo(expected, delta)927   *928   * Asserts that the target is equal `expected`, to within a +/- `delta` range.929   *930   *     expect(1.5).to.be.closeTo(1, 0.5);931   *932   * @name closeTo933   * @param {Number} expected934   * @param {Number} delta935   * @api public936   */937  Assertion.addMethod('closeTo', function (expected, delta) {938    var obj = flag(this, 'object');939    this.assert(940        Math.abs(obj - expected) <= delta941      , 'expected #{this} to be close to ' + expected + ' +/- ' + delta942      , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta943    );944  });...Using AI Code Generation
1var chai = require('chai');2var assert = chai.assert;3var expect = chai.expect;4var should = chai.should();5var chaiAsPromised = require('chai-as-promised');6chai.use(chaiAsPromised);7describe('assertLengthChain', function() {8  it('should test the length of an array', function() {9    var array = [1, 2, 3];10    expect(array).to.have.length(3);11  });12});13var chai = require('chai');14var assert = chai.assert;15var expect = chai.expect;16var should = chai.should();17var chaiAsPromised = require('chai-as-promised');18chai.use(chaiAsPromised);19describe('assertLengthChain', function() {20  it('should test the length of an array', function() {21    var array = [1, 2, 3];22    expect(array).to.have.length(3);23  });24});25var chai = require('chai');26var assert = chai.assert;27var expect = chai.expect;28var should = chai.should();29var chaiAsPromised = require('chai-as-promised');30chai.use(chaiAsPromised);31describe('assertLengthChain', function() {32  it('should test the length of an array', function() {33    var array = [1, 2, 3];34    expect(array).to.have.length(3);35  });36});37var chai = require('chai');38var assert = chai.assert;39var expect = chai.expect;40var should = chai.should();41var chaiAsPromised = require('chai-as-promised');42chai.use(chaiAsPromised);43describe('assertLengthChain', function() {44  it('should test the length of an array', function() {45    var array = [1, 2, 3];46    expect(array).to.have.length(3);47  });48});49var chai = require('chai');50var assert = chai.assert;51var expect = chai.expect;52var should = chai.should();Using AI Code Generation
1var assert = require('chai').assert;2var assertLengthChain = require('chai-assertlength');3assertLengthChain(assert);4var assert = require('chai').assert;5assert.lengthOf('foo', 3);6assert.lengthOf([1,2,3], 3, 'array has length of 3');7assert.lengthOf({ foo: 'bar', hello: 'universe' }, 2, 'object has length of 2');Using AI Code Generation
1var chai = require('chai');2var assert = chai.assert;3var expect = chai.expect;4var should = chai.should();5var chaiAsPromised = require('chai-as-promised');6chai.use(chaiAsPromised);7var assertLengthChain = require('../assertLengthChain');8describe('assertLengthChain', function() {9  it('should return true if the length of the array is equal to 3', function() {10    assert.isTrue(assertLengthChain([1, 2, 3]));11  });12  it('should return false if the length of the array is not equal to 3', function() {13    assert.isFalse(assertLengthChain([1, 2, 3, 4]));14  });15});16var chai = require('chai');17var assert = chai.assert;18var expect = chai.expect;19var should = chai.should();20var chaiAsPromised = require('chai-as-promised');21chai.use(chaiAsPromised);22var assertLengthChain = require('../assertLengthChain');23describe('assertLengthChain', function() {24  it('should return true if the length of the array is equal to 3', function() {25    assert.isTrue(assertLengthChain([1, 2, 3]));26  });27  it('should return false if the length of the array is not equal to 3', function() {28    assert.isFalse(assertLengthChain([1, 2, 3, 4]));29  });30});Using AI Code Generation
1const chai = require('chai');2const assert = chai.assert;3const expect = chai.expect;4const should = chai.should();5const assertLengthChain = require('chai-assert-length-chain');6chai.use(assertLengthChain);7describe('Test chai-assert-length-chain', function() {8  it('should have length of 3', function() {9    expect([1, 2, 3]).to.have.lengthOf(3);10  });11  it('should have length of 3 using assert', function() {12    assert.lengthOf([1, 2, 3], 3);13  });14  it('should have length of 3 using should', function() {15    [1, 2, 3].should.have.lengthOf(3);16  });17});Using AI Code Generation
1var assert = require('chai').assert;2var assertLengthChain = require('chai-assertlength');3assertLengthChain(assert);4assert.lengthOf([1,2,3], 3);5assert.lengthOf('foo', 3);6assert.lengthOf({a: 1, b: 2}, 2);7assert.lengthOf({length: 5}, 5);8assert.lengthOf(new Uint8Array(2), 2);9assert.lengthOf(new Map(), 0);10assert.lengthOf(new Set(), 0);11assert.lengthOf(new WeakMap(), 0);12assert.lengthOf(new WeakSet(), 0);13assert.lengthOf(new Array(3), 3);14assert.lengthOf(new String('foo'), 3);15assert.lengthOf(new Map([['a', 1], ['b', 2]]), 2);16assert.lengthOf(new Set([1, 2, 3]), 3);17assert.lengthOf(new WeakMap([[{}, 1], [{}, 2]]), 2);18assert.lengthOf(new WeakSet([{a: 1}, {b: 2}]), 2);19assert.lengthOf(new ArrayBuffer(2), 2);20assert.lengthOf(new DataView(new ArrayBuffer(2)), 2);21assert.lengthOf(new Float32Array(2), 2);22assert.lengthOf(new Float64Array(2), 2);23assert.lengthOf(new Int8Array(2), 2);Using AI Code Generation
1var chai = require('chai');2var assert = chai.assert;3var expect = chai.expect;4var should = chai.should();5describe('test', function() {6  it('test', function() {7    expect('test').to.have.lengthOf(4);8  });9});10var chai = require('chai');11var assert = chai.assert;12var expect = chai.expect;13var should = chai.should();14describe('test', function() {15  it('test', function() {16    expect('test').to.have.lengthOf(4);17  });18});19var chai = require('chai');20var assert = chai.assert;21var expect = chai.expect;22var should = chai.should();23describe('test', function() {24  it('test', function() {25    expect('test').to.have.lengthOf(4);26  });27});28var chai = require('chai');29var assert = chai.assert;30var expect = chai.expect;31var should = chai.should();32describe('test', function() {33  it('test', function() {34    expect('test').to.have.lengthOf(4);35  });36});37var chai = require('chai');38var assert = chai.assert;39var expect = chai.expect;40var should = chai.should();41describe('test', function() {42  it('test', function() {43    expect('test').to.have.lengthOf(4);44  });45});46var chai = require('chai');47var assert = chai.assert;48var expect = chai.expect;49var should = chai.should();50describe('test', function() {51  it('test', function() {52    expect('test').to.have.lengthOf(4);53  });54});55var chai = require('chai');56var assert = chai.assert;57var expect = chai.expect;58var should = chai.should();59describe('test', function() {60  it('test', function() {61    expect('test').to.have.lengthOf(4);62  });63});Using AI Code Generation
1var chai = require('chai');2var assert = chai.assert;3var expect = chai.expect;4var should = chai.should();5var assertLengthChain = function (str, length) {6    str.should.have.length(length);7};8assertLengthChain('hello', 5);9assertLengthChain('hello', 6);Using AI Code Generation
1var chai = require('chai');2var expect = chai.expect;3var assert = chai.assert;4var should = chai.should();5chai.use(require('chai-length'));6describe('Array', function() {7  describe('#length', function() {8    it('should return the length of the array', function() {9      var arr = [1,2,3];10      expect(arr).to.have.lengthOf(3);11      assert.lengthOf(arr, 3);12      arr.should.have.lengthOf(3);13    });14  });15});16var chai = require('chai');17var expect = chai.expect;18var assert = chai.assert;19var should = chai.should();20chai.use(require('chai-length'));21describe('Array', function() {22  describe('#length', function() {23    it('should return the length of the array', function() {24      var arr = [1,2,3];25      expect(arr).to.have.length(3);26      assert.lengthOf(arr, 3);27      arr.should.have.length(3);28    });29  });30});31var chai = require('chai');32var expect = chai.expect;33var assert = chai.assert;34var should = chai.should();35chai.use(require('chai-length'));36describe('Array', function() {37  describe('#length', function() {38    it('should return the length of the array', function() {39      var arr = [1,2,3];40      expect(arr).to.have.lengthOf.at.least(3);41      assert.lengthOf(arr, 3, 'length of array is 3');42      arr.should.have.lengthOf.at.least(3);43    });44  });45});46var chai = require('chai');Using AI Code Generation
1const assert = require('chai').assert;2const assertLengthChain = require('chai-assert-length-chain');3assertLengthChain(assert);4const arr = [1,2,3];5assert.lengthOf(arr, 3, 'array length is 3');6assert.lengthOf(arr, 4, 'array length is 4');7assert.lengthOf(arr, 4, 'array length is 4');8assert.lengthOf(arr, 3, 'array length is 3');Using AI Code Generation
1const assert = require('chai').assert;2const expect = require('chai').expect;3const should = require('chai').should();4let arr = [1, 2, 3];5describe('chai assert', function () {6  it('should assert length of array', function () {7    assert.lengthOf(arr, 3);8  });9});10describe('chai expect', function () {11  it('should assert length of array', function () {12    expect(arr).to.have.lengthOf(3);13  });14});15describe('chai should', function () {16  it('should assert length of array', function () {17    arr.should.have.lengthOf(3);18  });19});Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
