I am looking at example at https://github.com/mrdulin/react-act-examples/blob/master/sync.md
function App() {
let [counter, setCounter] = useState(0);
return <button onClick={() => setCounter(counter + 1)}>{counter}</button>;
}
test one, it works
it("should increment a counter", () => {
const el = document.createElement("div");
document.body.appendChild(el);
// we attach the element to document.body to ensure events work
ReactDOM.render(<App />, el);
const button = el.childNodes[0];
for (let i = 0; i < 3; i++) {
button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
}
expect(button.innerHTML).toBe("3");
});
test two, doesn't work
it("should increment a counter", () => {
const el = document.createElement("div");
document.body.appendChild(el);
// we attach the element to document.body to ensure events work
ReactDOM.render(<App />, el);
const button = el.childNodes[0];
act(() => {
for (let i = 0; i < 3; i++) {
button.dispatchEvent(new MouseEvent("click", { bubbles: true }));
}
});
expect(button.innerHTML).toBe(3); // this fails, it's actually "1"!
});
I still don't understand how first testworks, as the author mentions that:
if the handlers are ever called close to each other, it's possible that the handler will use stale data and miss some increments
then why the first test doesn't subject to this rule? why it doesn't use stale data like test two?