From 073717122cbe1275d6b8346c2d25b78c353ef333 Mon Sep 17 00:00:00 2001 From: Denis Bardadym Date: Sat, 10 Dec 2016 13:35:27 +0300 Subject: [PATCH] Add a bit hacky error to throw instead of full powered AssertionError --- lib/assertion.js | 35 +++++++++++++++++++++++++++++++++-- test/not.test.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 test/not.test.js diff --git a/lib/assertion.js b/lib/assertion.js index ffe5053..7a6b04d 100644 --- a/lib/assertion.js +++ b/lib/assertion.js @@ -6,6 +6,30 @@ */ import AssertionError from './assertion-error'; +import { merge } from 'should-util'; + + +// a bit hacky way how to get error to do not have stack +function LightAssertionError(options) { + merge(this, options); + + if (!options.message) { + Object.defineProperty(this, 'message', { + get: function() { + if (!this._message) { + this._message = this.generateMessage(); + this.generatedMessage = true; + } + return this._message; + } + }); + } +} + +LightAssertionError.prototype = { + generateMessage: AssertionError.prototype.generateMessage +}; + /** * should Assertion @@ -69,7 +93,11 @@ Assertion.prototype = { params.assertion = this; - throw new AssertionError(params); + if (this.light) { + throw new LightAssertionError(params); + } else { + throw new AssertionError(params); + } }, /** @@ -142,12 +170,13 @@ Assertion.add = function(name, func) { value: function() { var context = new Assertion(this.obj, this, name); context.anyOne = this.anyOne; + context.light = true; try { func.apply(context, arguments); } catch (e) { // check for fail - if (e instanceof AssertionError) { + if (e instanceof AssertionError || e instanceof LightAssertionError) { // negative fail if (this.negate) { this.obj = context.obj; @@ -161,6 +190,7 @@ Assertion.add = function(name, func) { // positive fail context.negate = false; + context.light = false; context.fail(); } // throw if it is another exception @@ -171,6 +201,7 @@ Assertion.add = function(name, func) { if (this.negate) { context.negate = true; // because .fail will set negate context.params.details = 'false negative fail'; + context.light = false; context.fail(); } diff --git a/test/not.test.js b/test/not.test.js new file mode 100644 index 0000000..133842b --- /dev/null +++ b/test/not.test.js @@ -0,0 +1,28 @@ +var should = require('../'); +var err = require('./util').err; + + +var a = 10; +var b = 11; + +describe('.not', function() { + it('should not throw when true', function() { + a.should.be.exactly(a); + }); + + it('should throw when false', function() { + err(function() { + a.should.be.exactly(b); + }, 'expected 10 to be 11'); + }); + + it('should throw when not true (false negative case)', function() { + err(function() { + a.should.not.be.exactly(a); + }, 'expected 10 not to be 10 (false negative fail)'); + }); + + it('should not throw when not false', function() { + a.should.not.be.exactly(b); + }); +});