You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写测试用例验证多次点击递减按钮后counter值不小于0

解决方法

你只需要先把text()获取到的字符串类型的计数器值,转换为数值类型再做断言即可,实现步骤如下:

  1. 调用trim()先清除获取到的文本首尾的空白字符,避免转换异常
  2. 用Number()、一元运算符+或者parseInt()把字符串转为数值
  3. 模拟多次点击递减按钮后,对转换后的数值直接使用toBeGreaterThanOrEqual匹配器做断言

参考测试用例

import { mount } from 'enzyme';
import Counter from './Counter';

test('多次点击递减按钮后计数器值始终不小于0', () => {
  const wrapper = mount(<Counter />);
  // 自定义点击次数,覆盖初始值为0、大于0的所有场景
  const clickTimes = 10;
  for (let i = 0; i < clickTimes; i++) {
    wrapper.find('.decrease-btn').simulate('click');
    // 转换文本为数值
    const counterValue = Number(wrapper.find('.counter-display').text().trim());
    // 断言计数器值不小于0
    expect(counterValue).toBeGreaterThanOrEqual(0);
  }
});

如果你的计数器展示有额外格式化文本(比如前缀Count: ),可以用正则提取数字部分再转换:

const counterText = wrapper.find('.counter-display').text().trim();
const counterValue = Number(counterText.match(/\d+/)[0]);

内容的提问来源于stack exchange,提问作者kichu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 12:54:03