import React from 'react'; import { render, unmountComponentAtNode } from 'react-dom'; import Timer from '../Timer';

describe('Timer', () => { let container = null;

beforeEach(() => { // 设置一个 DOM 元素作为渲染目标 container = document.createElement('div'); document.body.appendChild(container); });

afterEach(() => { // 清理 onmount 事件 unmountComponentAtNode(container); container.remove(); container = null; });

it('renders without crashing', () => { render(, container); });

it('starts timer correctly', () => { const leftTime = 60; render(, container);

// 获取显示时间的元素
const timerBox = container.querySelector('.timerBox');
const hoursElement = timerBox.querySelector('.block:nth-child(2)');
const minutesElement = timerBox.querySelector('.block:nth-child(4)');
const secondsElement = timerBox.querySelector('.block:nth-child(6)');

// 等待 1 秒
setTimeout(() => {
  // 获取更新后的时间
  const hours = parseInt(hoursElement.textContent);
  const minutes = parseInt(minutesElement.textContent);
  const seconds = parseInt(secondsElement.textContent);

  // 断言时间是否正确
  expect(hours).toBe(0);
  expect(minutes).toBe(0);
  expect(seconds).toBe(59);
}, 1000);

});

it('calls onReload when leftTime is negative', () => { const onReload = jest.fn(); const leftTime = -1; render(, container);

// 等待 1 秒
setTimeout(() => {
  // 断言 onReload 是否被调用
  expect(onReload).toHaveBeenCalled();
}, 1000);

}); });


原文地址: https://www.cveoy.top/t/topic/hJkP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录