samedi 25 février 2017

Testing dates in JS

date.js

class DateHelper {
  constructor() {
    this.months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
  }

  postedOn(from) {
    const date = new Date(from);
    const day = date.getDate();
    const month = this.months[date.getMonth()];
    const year = date.getFullYear();
    if (year === new Date().getFullYear()) {
      return `${day} ${month}`;
    }
    return `${day} ${month} ${year}`;
  }
}

date_spec.js

describe('', () => {
  it('', () => {
    const from = 'Wed Feb 25 2015 00:38:24 GMT+0200 (EET)';
    expect(newDateHelper.postedOn(from)).to.equal('25 Feb 2015');
  });
  it('', () => {
    const from = 'Wed Feb 25 2017 00:38:24 GMT+0200 (EET)';
    expect(newDateHelper.postedOn(from)).to.equal('25 Feb');
  });
});

All tests are currently passing, but because postedOn compares to the current year I will need to update those tests each year. How can I fix this?

Aucun commentaire:

Enregistrer un commentaire