From e6ddf64c8f778563d42911386cd05432d1d84ce4 Mon Sep 17 00:00:00 2001 From: Grant Snodgrass Date: Sat, 10 Jun 2017 17:51:50 -0400 Subject: [PATCH] fix: check target's type in `.property` assertion Previously, the `.property` assertion failed ungracefully if the target was `null` or `undefined`. This commit causes an `AssertionError` to be thrown instead so that the ssfi flag and custom error messages are respected. --- lib/chai/core/assertions.js | 11 ++++++++++- test/assert.js | 8 ++++++++ test/expect.js | 8 ++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/chai/core/assertions.js b/lib/chai/core/assertions.js index d6c0be6..0e15722 100644 --- a/lib/chai/core/assertions.js +++ b/lib/chai/core/assertions.js @@ -1644,6 +1644,7 @@ module.exports = function (chai, _) { var isNested = flag(this, 'nested') , isOwn = flag(this, 'own') , flagMsg = flag(this, 'message') + , obj = flag(this, 'object') , ssfi = flag(this, 'ssfi'); if (isNested && isOwn) { @@ -1655,9 +1656,17 @@ module.exports = function (chai, _) { ); } + if (obj === null || obj === undefined) { + flagMsg = flagMsg ? flagMsg + ': ' : ''; + throw new AssertionError( + flagMsg + 'Target cannot be null or undefined.', + undefined, + ssfi + ); + } + var isDeep = flag(this, 'deep') , negate = flag(this, 'negate') - , obj = flag(this, 'object') , pathInfo = isNested ? _.getPathInfo(obj, name) : null , value = isNested ? pathInfo.value : obj[name]; diff --git a/test/assert.js b/test/assert.js index 9cfff71..9a36f59 100644 --- a/test/assert.js +++ b/test/assert.js @@ -1339,6 +1339,14 @@ describe('assert', function () { err(function () { assert.notNestedPropertyVal(obj, 'foo.bar', 'baz', 'blah'); }, "blah: expected { foo: { bar: 'baz' } } to not have nested property 'foo.bar' of 'baz'"); + + err(function () { + assert.property(null, 'a', 'blah'); + }, "blah: Target cannot be null or undefined."); + + err(function () { + assert.property(undefined, 'a', 'blah'); + }, "blah: Target cannot be null or undefined."); }); it('deepPropertyVal', function () { diff --git a/test/expect.js b/test/expect.js index 2194110..6f3f45d 100644 --- a/test/expect.js +++ b/test/expect.js @@ -1263,6 +1263,14 @@ describe('expect', function () { err(function() { expect({a: {b: 1}}, 'blah').to.have.own.nested.property("a.b"); }, "blah: The \"nested\" and \"own\" flags cannot be combined."); + + err(function () { + expect(null, 'blah').to.have.property("a"); + }, "blah: Target cannot be null or undefined."); + + err(function () { + expect(undefined, 'blah').to.have.property("a"); + }, "blah: Target cannot be null or undefined."); }); it('property(name, val)', function(){