简体   繁体   中英

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?

您如何看待模板字面量以及如何获取当前年份?

const from = `Wed Feb 25 ${new Date().getFullYear()} 00:38:24 GMT+0200 (EET)`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM