Skip to content

Commit

Permalink
Make utils.getName more robust & use it in empty (#813)
Browse files Browse the repository at this point in the history
* use utils.getName

* remove extra .to in tests

* make getName even more robust

* add basic tests
  • Loading branch information
shvaikalesh authored and meeber committed Oct 2, 2016
1 parent 809ac3e commit fdd0f8c
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 4 deletions.
4 changes: 2 additions & 2 deletions lib/chai/core/assertions.js
Original file line number Diff line number Diff line change
Expand Up @@ -544,8 +544,8 @@ module.exports = function (chai, _) {
case 'weakset':
throw new TypeError('.empty was passed a weak collection');
case 'function':
var name = val.name ? ' ' + val.name : '';
throw new TypeError('.empty was passed a function' + name);
var msg = '.empty was passed a function ' + _.getName(val);
throw new TypeError(msg.trim());
default:
if (val !== Object(val)) {
throw new TypeError('.empty was passed non-string primitive ' + _.inspect(val));
Expand Down
3 changes: 2 additions & 1 deletion lib/chai/utils/getName.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@
* @name getName
*/

var toString = Function.prototype.toString;
var functionNameMatch = /\s*function(?:\s|\s*\/\*[^(?:*\/)]+\*\/\s*)*([^\s\(\/]+)/;

module.exports = function (func) {
var name = '';
if (typeof func.name === 'undefined') {
// Here we run a polyfill if func.name is not defined
var match = String(func).match(functionNameMatch);
var match = toString.call(func).match(functionNameMatch);
if (match) {
name = match[1];
}
Expand Down
2 changes: 1 addition & 1 deletion test/should.js
Original file line number Diff line number Diff line change
Expand Up @@ -734,7 +734,7 @@ describe('should', function() {
}, ".empty was passed non-string primitive Symbol()");

err(function(){
Symbol.iterator.should.to.be.empty;
Symbol.iterator.should.be.empty;
}, ".empty was passed non-string primitive Symbol(Symbol.iterator)");
}

Expand Down
14 changes: 14 additions & 0 deletions test/utilities.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@ describe('utilities', function () {
});
});

it('getName', function () {
chai.use(function (_chai, utils) {
var name = utils.getName;
expect(name(function () {})).to.equal('');
expect(name(function foo() {})).to.equal('foo');

var bar = function bar() {};
bar.toString = function() {
return 'function foo() {}';
};

expect(name(bar)).to.equal('bar');
});
});

it('getPathValue', function () {
var object = {
Expand Down

0 comments on commit fdd0f8c

Please sign in to comment.