Skip to content
This repository has been archived by the owner on Nov 4, 2020. It is now read-only.

Commit

Permalink
Add a bit hacky error to throw instead of full powered AssertionError
Browse files Browse the repository at this point in the history
  • Loading branch information
btd committed Dec 10, 2016
1 parent 63c9b56 commit 0737171
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 2 deletions.
35 changes: 33 additions & 2 deletions lib/assertion.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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);
}
},

/**
Expand Down Expand Up @@ -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;
Expand All @@ -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
Expand All @@ -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();
}

Expand Down
28 changes: 28 additions & 0 deletions test/not.test.js
Original file line number Diff line number Diff line change
@@ -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);
});
});

0 comments on commit 0737171

Please sign in to comment.