main.js
let timeContent = () => {
let content = '';
let nowDate = new Date();
let nowDay = nowDate.getDay();
let nowHours = nowDate.getHours();
let nowMinutes = nowDate.getMinutes();
let nowSeconds = nowDate.getSeconds();
if (nowDay === 0 || nowDay === 6) {
content = '距离周末还有0天';
} else {
content = `距离周末还有<span>${5-nowDay}天${23-nowHours}时${59-nowMinutes}分${59-nowSeconds}秒</span> `;
}
return content;
};
main.test.js
const timeContent = require('../src/main.js');
test('返回值是否包含距离周末还有', () => {
expect(timeContent()).toMatch('距离周末还有');
});
###
需要mock Date
构造函数,并返回确定的时间,测试结果必须是可预测的,否则是不可测试的。
main.js
:
let timeContent = () => {
let content = '';
let nowDate = new Date();
let nowDay = nowDate.getDay();
let nowHours = nowDate.getHours();
let nowMinutes = nowDate.getMinutes();
let nowSeconds = nowDate.getSeconds();
if (nowDay === 0 || nowDay === 6) {
content = '距离周末还有0天';
} else {
content = `距离周末还有<span>${5 - nowDay}天${23 - nowHours}时${59 - nowMinutes}分${59 - nowSeconds}秒</span>`;
}
return content;
};
module.exports = timeContent;
const timeContent = require('./main');
describe('1010000022139507', () => {
it('should pass', () => {
const mockedDate = new Date(2020, 4, 9, 0, 0);
const DateMock = jest.spyOn(global, 'Date').mockImplementationOnce(() => mockedDate);
const actual = timeContent();
expect(actual).toBe('距离周末还有0天');
DateMock.mockRestore();
});
it('should pass 2', () => {
const mockedDate = new Date(2020, 4, 8, 0, 0);
const DateMock = jest.spyOn(global, 'Date').mockImplementationOnce(() => mockedDate);
const actual = timeContent();
expect(actual).toBe('距离周末还有<span>0天23时59分59秒</span>');
DateMock.mockRestore();
});
});
测试结果+测试覆盖率报告:
PASS segmentfault/1010000022139507/main.test.js (10.512s)
1010000022139507
? should pass (4ms)
? should pass 2
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
main.js | 100 | 100 | 100 | 100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 12.487s