-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseConstructor.cy.tsx
More file actions
69 lines (54 loc) · 2 KB
/
useConstructor.cy.tsx
File metadata and controls
69 lines (54 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import React, { useState } from "react";
import { useConstructor } from "../../src/lib/hooks/useConstructor";
describe("useConstructor", () => {
it("calls the callback exactly once per mount, even after re-renders", () => {
const initSpy = cy.spy().as("initSpy");
const TestComponent: React.FC = () => {
const [count, setCount] = useState(0);
useConstructor(() => {
initSpy();
});
return (
<div>
<span data-cy="count">{count}</span>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
</div>
);
};
// Turn off StrictMode as it will double‑invoke mount logic
cy.mount(<TestComponent />, { strict: false });
cy.get("@initSpy").should("have.been.calledOnce");
// Cause several re-renders
cy.contains("Increment").click();
cy.contains("Increment").click();
cy.contains("Increment").click();
cy.get("[data-cy='count']").should("have.text", "3");
cy.get("@initSpy").should("have.been.calledOnce");
});
it("runs again after an unmount/remount (new instance)", () => {
const initSpy = cy.spy().as("initSpy");
const Wrapper: React.FC = () => {
const [show, setShow] = useState(true);
return (
<div>
<button onClick={() => setShow((s) => !s)}>Toggle</button>
{show && <Child />}
</div>
);
};
const Child: React.FC = () => {
useConstructor(() => {
initSpy();
});
return <div data-cy="child">Child</div>;
};
// Turn off StrictMode as it will double‑invoke mount logic
cy.mount(<Wrapper />, { strict: false });
cy.get("@initSpy").should("have.been.calledOnce");
cy.contains("Toggle").click(); // unmount
cy.get("[data-cy='child']").should("not.exist");
cy.contains("Toggle").click(); // remount
cy.get("[data-cy='child']").should("exist");
cy.get("@initSpy").should("have.callCount", 2);
});
});