【问题标题】:I am having hard time writing Jest test for timer我很难为计时器编写 Jest 测试
【发布时间】:2019-07-29 15:13:06
【问题描述】:

我正在尝试为 react-countdown-now 计时器编写笑话测试。它应该很简单,但我是个玩笑新手,我很难写。

import React from 'react';
import ReactDOM from 'react-dom';
import Countdown, { zeroPad } from 'react-countdown-now';
import "./TimeOut.scss";
 
const renderer = ({ minutes, seconds, completed }) => {
  return <div><span>{zeroPad(minutes, 2)}:{zeroPad(seconds, 2)}</span></div>;
};

class Timer extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      timeout: props.timeout * 60 * 1000
    };
  }

  render() {
    return (
      <Countdown
        date={Date.now() + this.state.timeout}
        renderer={renderer}/>
    );
  }
}

export default Timer;

【问题讨论】:

  • 你到底想测试什么?
  • 目前,有一个 10 分钟的计时器,由于不活动,您将被注销。所以我应该测试它是否正常工作。
  • 好的,请包括您目前的测试。
  • 我写的有什么意义吗?

标签: reactjs jestjs


【解决方案1】:

在我的代码中,我有一个函数 WaitFor() 应该暂停代码并延迟几秒钟。为了测试,我会这样做:

describe('WaitFor Testing', () => {
    it('should take at least 3 seconds to execute the test', () => {
        const Start:number = moment.now();
        WaitFor(3)
        const Duration = (moment.now() - Start);
        expect(Duration).toBeGreaterThan(2000);
        expect(Duration).toBeLessThan(10000);
    });
});

这会导致代码等待并看到时钟至少等待了接近三秒。

Jest 可以关注Jest Timer Mocks

// __tests__/timerGame-test.js
'use strict';

jest.useFakeTimers();

test('waits 1 second before ending the game', () => {
    const timerGame = require('../timerGame');
    timerGame();

    expect(setTimeout).toHaveBeenCalledTimes(1);
    expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 2022-01-23
    • 2021-12-03
    • 1970-01-01
    • 2018-11-30
    • 2019-10-05
    • 2020-10-12
    相关资源
    最近更新 更多