Skip to content

Commit 69b8552

Browse files
author
Joao Madeiras
committed
Add support for timestamp on date assert
1 parent d58a900 commit 69b8552

File tree

2 files changed

+24
-8
lines changed

2 files changed

+24
-8
lines changed

src/asserts/date-assert.js

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,24 @@ export default function dateAssert() {
2121
*/
2222

2323
this.validate = value => {
24-
if (typeof value !== 'string' && Object.prototype.toString.call(value) !== '[object Date]') {
25-
throw new Violation(this, value, { value: 'must_be_a_date_or_a_string' });
24+
if (typeof value === 'string') {
25+
if (isNaN(Date.parse(value)) === true) {
26+
throw new Violation(this, value);
27+
}
28+
29+
return true;
30+
}
31+
32+
if (typeof value === 'number') {
33+
if (new Date(value).getTime() < 0) {
34+
throw new Violation(this, value);
35+
}
36+
37+
return true;
2638
}
2739

28-
if (isNaN(Date.parse(value)) === true) {
29-
throw new Violation(this, value);
40+
if (Object.prototype.toString.call(value) !== '[object Date]') {
41+
throw new Violation(this, value, { value: 'must_be_a_date_or_a_string_or_a_timestamp' });
3042
}
3143

3244
return true;

test/asserts/date-assert_test.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,9 @@ const Assert = BaseAssert.extend({
1919
* Test `DateAssert`.
2020
*/
2121

22-
describe('DateAssert', () => {
23-
it('should throw an error if the input value is not a string or a date', () => {
24-
const choices = [[], {}, 123];
22+
describe.only('DateAssert', () => {
23+
it('should throw an error if the input value is not a date or a string or a timestamp', () => {
24+
const choices = [[], {}];
2525

2626
choices.forEach(choice => {
2727
try {
@@ -30,7 +30,7 @@ describe('DateAssert', () => {
3030
should.fail();
3131
} catch (e) {
3232
e.should.be.instanceOf(Violation);
33-
e.violation.value.should.equal('must_be_a_date_or_a_string');
33+
e.violation.value.should.equal('must_be_a_date_or_a_string_or_a_timestamp');
3434
}
3535
});
3636
});
@@ -52,4 +52,8 @@ describe('DateAssert', () => {
5252
it('should accept a `string`', () => {
5353
new Assert().Date().validate('2014-10-16');
5454
});
55+
56+
it('should accept a `timestamp`', () => {
57+
new Assert().Date().validate(Date.now());
58+
});
5559
});

0 commit comments

Comments
 (0)