Reputation: 151
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)
}
})
});
how to write a test case to test that counter value will not be less than 0 even if decrement button is pressed many times without any if condition how to use toBeGreaterThanOrEqual
here it is expecting a number value but I am getting a string value
Upvotes: 0
Views: 1043
Reputation: 102307
.text() => String returns a string NOT number.
You don't have to use if condition in your test case.
setCouter(counter > 0 ? counter - 1 : 0)
This statement ensures that the counter
state will not be less than 0
. This is what you are testing. To test this, we can mount the component firstly, the initial state of the counter
is 0
, and simulate the user clicking the decrease button multiple times and assert that the counter
state displayed is 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');
});
});
Test result:
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
Upvotes: 1