timestring/test.js

64 lines
1.8 KiB
JavaScript
Raw Normal View History

2014-07-18 00:13:01 +02:00
var chai = require('chai');
var expect = chai.expect;
2015-05-01 18:31:25 +02:00
2016-01-15 11:00:12 +01:00
var timestring = require('./index');
2014-07-18 00:13:01 +02:00
describe('timestring', function() {
2015-05-01 18:31:25 +02:00
it('can parse a timestring', function() {
var ts = new timestring();
expect(ts.parse('1s')).to.equal(1);
expect(ts.parse('1m')).to.equal(60);
expect(ts.parse('1h')).to.equal(3600);
expect(ts.parse('1d')).to.equal(86400);
expect(ts.parse('1w')).to.equal(604800);
expect(ts.parse('1mth')).to.equal(2419200);
expect(ts.parse('1y')).to.equal(29030400);
});
2015-05-01 18:31:25 +02:00
it('can return a value in a specified unit', function() {
expect((new timestring()).parse('5m', 's')).to.equal(300);
expect((new timestring()).parse('5m', 'm')).to.equal(5);
});
2016-01-15 12:00:03 +01:00
it('uses the passed options instead of the defaults', function() {
var opts = {
hoursPerDay: 1,
daysPerWeek: 2,
weeksPerMonth: 3,
monthsPerYear: 4
};
2016-01-15 12:00:03 +01:00
var ts = new timestring(opts);
expect(ts.parse('1d', 'h')).to.equal(1);
expect(ts.parse('1w', 'd')).to.equal(2);
expect(ts.parse('1mth', 'w')).to.equal(3);
expect(ts.parse('1y', 'mth')).to.equal(4);
});
2015-05-01 18:31:25 +02:00
it('throws an error when an invalid unit is used in the timestring', function() {
var ts = new timestring();
expect(ts.parse.bind(ts, '1g')).to.throw(Error);
});
2015-05-01 18:31:25 +02:00
it('can parse a messy time string', function() {
expect((new timestring()).parse('5 D a YS 4 h 2 0 mI nS')).to.equal(447600);
});
2015-05-01 18:31:25 +02:00
it('should expose a method on String.prototype that will parse the string as a timestring', function(){
2014-07-18 00:13:01 +02:00
var str = '1min';
// no arguments passed
expect(str.parseTime()).to.equal(60);
// units argument passed
expect(str.parseTime('m')).to.equal(1);
2016-01-15 12:00:03 +01:00
// units + options argument passed
2014-07-18 00:13:01 +02:00
str = '5h';
expect(str.parseTime('d', { hoursPerDay: 5 })).to.equal(1);
});
});