如何制作测试用例以检查计数器的值即使按下递减按钮也不会小于零

how to make a test case to check the value of counter will not be less than zero even if decrement button is pressed

counter.js

import React from "react";

export default function Counter() {
  const [counter , setCouter]  = React.useState(0);
  return (
    <div className="App">
     <h1>This is Counter App of me</h1>
     <div id="counter-value">{counter}</div>
     <button id="increment-btn" onClick={() => setCouter(counter + 1)}>Increment</button>
     <button id="decrement-btn" onClick={() => setCouter(counter > 0 ? counter - 1 : 0)}>Decrement</button>
    </div>
  );
}

app.js

import React from "react";
import "./App.css";
import Counter from "./Counter";

function App() {
 
  return (
    <div className="App">
    <Counter/>
    </div>
  );
}

export default App;

app.test.js

import React from "react";
import { mount } from "enzyme";
import App from "./App";
import Counter from "./Counter"
import { shallow } from 'enzyme';

describe("Counter Testing", () => {
  let wrapper;
  beforeEach(() => {
    wrapper = mount(<App/>)
  })


test("render the click event of decrement button of and check the counter value cannot be less than 0" , () => {
  if(wrapper.find("#counter-value").text() === "0"){
     wrapper.find("#decrement-btn").simulate("click")
   expect(wrapper.find("#counter-value").text()).toBe("0")
  //  expect(wrapper.find("#counter-value").text()).toBeGreaterThanOrEqual(0)
  }
})
});


如何编写测试用例来测试计数器值不会小于 0,即使在没有任何 if 条件的情况下多次按下递减按钮如何使用 toBeGreaterThanOrEqual 这里需要一个数字值但是我得到一个字符串值

.text() => String returns 一个字符串 不是 数字。

您不必在测试用例中使用 if 条件。

setCouter(counter > 0 ? counter - 1 : 0)

这个语句保证counter状态不会小于0。这就是你正在测试的。为了测试这个,我们可以先挂载组件,counter的初始状态是0,模拟用户多次点击减少按钮并断言显示的counter状态是0.

import React from 'react';
import { mount } from 'enzyme';
import App from './App';

describe('Counter Testing', () => {
  let wrapper;
  beforeEach(() => {
    wrapper = mount(<App />);
  });

  test('render the click event of decrement button of and check the counter value cannot be less than 0', () => {
    const decrementButton = wrapper.find('#decrement-btn');
    decrementButton.simulate('click');
    decrementButton.simulate('click');
    expect(wrapper.find('#counter-value').text()).toBe('0');
  });
});

测试结果:

 PASS  examples/70112961/app.test.js (10.102 s)
  Counter Testing
    ✓ render the click event of decrement button of and check the counter value cannot be less than 0 (40 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.088 s, estimated 12 s