2017-02-25 24 views
1

date.js 测试在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'); 
    }); 
}); 

所有的测试都通过当前,但由于postedOn比较当年我将需要更新这些测试每年。我怎样才能解决这个问题?

回答

2

你怎么看待模板文字,并在其中获得当年?

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

没想过。感谢您的帮助) –

+0

@ArtemGurzhii如果没关系,您可以将答案标记为正确) – Antonio