Skip to content

Commit

Permalink
fix: tests
Browse files Browse the repository at this point in the history
  • Loading branch information
zetxx committed Jun 4, 2021
1 parent 684cae6 commit 333fbd7
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 5 deletions.
18 changes: 14 additions & 4 deletions lib/error/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ const flatten = require('flat');

const CreateError = ({code, parent, message}) => {
class CustomError extends (parent || Error) {
constructor(message = code, props = {state: null}) {
super(message);
constructor(innerMessage = message, props = {state: null}) {
super(innerMessage);
let {state, id} = props;
this.data = {
state: null,
id: null
};
// Maintains proper stack trace for where our error was thrown (only available on V8)
Error.captureStackTrace && Error.captureStackTrace(this, CustomError);

Expand All @@ -13,10 +17,16 @@ const CreateError = ({code, parent, message}) => {
id && (this.id = id);
}
set state(state) {
state && (this.state = {...(this.state || {}), ...flatten(state)});
state && (this.data.state = {...(this.data.state || {}), ...flatten(state)});
}
get state() {
return this.data.state;
}
set id(id) {
id && (this.id = id);
id && (this.data.id = id);
}
get id() {
return this.data.id;
}
}
return CustomError;
Expand Down
24 changes: 24 additions & 0 deletions tests/unit/error/test.error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const tap = require('tap');
const CustomError = require('../../../lib/error');

const A = CustomError({code: 'A', message: 'msg-a'});
const B = CustomError({code: 'B', parent: A, message: 'msg-b'});

tap.test('Error', (t) => {
t.type(CustomError, 'function', 'should be function');
t.type(A, 'function', 'should be function');
t.type(B, 'function', 'should be function');
const a1 = new A();
const a2 = new A('msg-a-2');
const a3 = new A('msg-a-3', {state: {a: 3}});
const b1 = new B();
t.equal(a1.message, 'msg-a', 'message should match');
t.equal(a1.state, null, 'state should be null');
t.equal(a2.message, 'msg-a-2', 'message should match');
t.equal(a3.message, 'msg-a-3', 'message should match');
t.same(a3.state, {a: 3}, 'state should match');
t.equal(a1.code, 'A', 'code should match');
t.equal(b1.code, 'A.B', 'code should match');
t.end();
});

3 changes: 2 additions & 1 deletion tests/unit/index.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
require('./method/test.index');
require('./error/test.error');
require('./method/test.method');
// require('./all/test.index');
File renamed without changes.

0 comments on commit 333fbd7

Please sign in to comment.