From 69b85521dd7d68d9c063f74edb26483152f52f9f Mon Sep 17 00:00:00 2001 From: Joao Madeiras Date: Sun, 10 Apr 2016 22:25:14 +0100 Subject: [PATCH] Add support for timestamp on date assert --- src/asserts/date-assert.js | 20 ++++++++++++++++---- test/asserts/date-assert_test.js | 12 ++++++++---- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/asserts/date-assert.js b/src/asserts/date-assert.js index 9457cf0..44af173 100644 --- a/src/asserts/date-assert.js +++ b/src/asserts/date-assert.js @@ -21,12 +21,24 @@ export default function dateAssert() { */ this.validate = value => { - if (typeof value !== 'string' && Object.prototype.toString.call(value) !== '[object Date]') { - throw new Violation(this, value, { value: 'must_be_a_date_or_a_string' }); + if (typeof value === 'string') { + if (isNaN(Date.parse(value)) === true) { + throw new Violation(this, value); + } + + return true; + } + + if (typeof value === 'number') { + if (new Date(value).getTime() < 0) { + throw new Violation(this, value); + } + + return true; } - if (isNaN(Date.parse(value)) === true) { - throw new Violation(this, value); + if (Object.prototype.toString.call(value) !== '[object Date]') { + throw new Violation(this, value, { value: 'must_be_a_date_or_a_string_or_a_timestamp' }); } return true; diff --git a/test/asserts/date-assert_test.js b/test/asserts/date-assert_test.js index dfffbbf..2f044ef 100644 --- a/test/asserts/date-assert_test.js +++ b/test/asserts/date-assert_test.js @@ -19,9 +19,9 @@ const Assert = BaseAssert.extend({ * Test `DateAssert`. */ -describe('DateAssert', () => { - it('should throw an error if the input value is not a string or a date', () => { - const choices = [[], {}, 123]; +describe.only('DateAssert', () => { + it('should throw an error if the input value is not a date or a string or a timestamp', () => { + const choices = [[], {}]; choices.forEach(choice => { try { @@ -30,7 +30,7 @@ describe('DateAssert', () => { should.fail(); } catch (e) { e.should.be.instanceOf(Violation); - e.violation.value.should.equal('must_be_a_date_or_a_string'); + e.violation.value.should.equal('must_be_a_date_or_a_string_or_a_timestamp'); } }); }); @@ -52,4 +52,8 @@ describe('DateAssert', () => { it('should accept a `string`', () => { new Assert().Date().validate('2014-10-16'); }); + + it('should accept a `timestamp`', () => { + new Assert().Date().validate(Date.now()); + }); });