返回 一个字符串,jest单元测试要怎么断言,如下代码

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('距离周末还有');
});
阅读 2.6k
1 个回答

需要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
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏