Skip to content

Commit

Permalink
Add support for timestamp on date assert
Browse files Browse the repository at this point in the history
  • Loading branch information
Joao Madeiras committed Apr 10, 2016
1 parent d58a900 commit 69b8552
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 8 deletions.
20 changes: 16 additions & 4 deletions src/asserts/date-assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
12 changes: 8 additions & 4 deletions test/asserts/date-assert_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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');
}
});
});
Expand All @@ -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());
});
});

0 comments on commit 69b8552

Please sign in to comment.