Skip to content

Commit dc99847

Browse files
Tweak test strategy for hooks under prop changes
1 parent 0938678 commit dc99847

File tree

1 file changed

+52
-21
lines changed

1 file changed

+52
-21
lines changed

src/components/Elements.test.tsx

Lines changed: 52 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -139,17 +139,35 @@ describe('Elements', () => {
139139
});
140140

141141
test('allows a transition from null to a valid Stripe object', () => {
142-
let stripeProp: any = null;
143-
const wrapper = ({children}: any) => (
144-
<Elements stripe={stripeProp}>{children}</Elements>
142+
const TestComponent = () => {
143+
const elements = useElements();
144+
145+
if (!elements) {
146+
return null;
147+
}
148+
149+
if (elements === mockElements) {
150+
return <>expected</>;
151+
}
152+
153+
throw new Error(`unexpected useElements value: ${elements}`);
154+
};
155+
156+
const {container, rerender} = render(
157+
<Elements stripe={null}>
158+
<TestComponent />
159+
</Elements>
145160
);
146161

147-
const {result, rerender} = renderHook(() => useElements(), {wrapper});
148-
expect(result.current).toBe(null);
162+
expect(container).toBeEmpty();
149163

150-
stripeProp = mockStripe;
151-
rerender();
152-
expect(result.current).toBe(mockElements);
164+
rerender(
165+
<Elements stripe={mockStripe}>
166+
<TestComponent />
167+
</Elements>
168+
);
169+
170+
expect(container).toHaveTextContent('expected');
153171
});
154172

155173
test('works with a Promise resolving to a valid Stripe object', async () => {
@@ -169,24 +187,37 @@ describe('Elements', () => {
169187
});
170188

171189
test('allows a transition from null to a valid Promise', async () => {
172-
let stripeProp: any = null;
173-
const wrapper = ({children}: any) => (
174-
<Elements stripe={stripeProp}>{children}</Elements>
175-
);
190+
const TestComponent = () => {
191+
const elements = useElements();
176192

177-
const {result, rerender, waitForNextUpdate} = renderHook(
178-
() => useElements(),
179-
{wrapper}
193+
if (!elements) {
194+
return null;
195+
}
196+
197+
if (elements === mockElements) {
198+
return <>expected</>;
199+
}
200+
201+
throw new Error(`unexpected useElements value: ${elements}`);
202+
};
203+
204+
const {container, rerender, findByText} = render(
205+
<Elements stripe={null}>
206+
<TestComponent />
207+
</Elements>
180208
);
181-
expect(result.current).toBe(null);
182209

183-
stripeProp = mockStripePromise;
184-
rerender();
185-
expect(result.current).toBe(null);
210+
expect(container).toBeEmpty();
186211

187-
await waitForNextUpdate();
212+
rerender(
213+
<Elements stripe={mockStripePromise}>
214+
<TestComponent />
215+
</Elements>
216+
);
188217

189-
expect(result.current).toBe(mockElements);
218+
expect(container).toBeEmpty();
219+
220+
await findByText('expected');
190221
});
191222

192223
test('does not set context if Promise resolves after Elements is unmounted', async () => {

0 commit comments

Comments
 (0)