Skip to content

Commit

Permalink
Tweak test strategy for hooks under prop changes
Browse files Browse the repository at this point in the history
  • Loading branch information
christopher-stripe committed Jun 1, 2020
1 parent 0938678 commit dc99847
Showing 1 changed file with 52 additions and 21 deletions.
73 changes: 52 additions & 21 deletions src/components/Elements.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -139,17 +139,35 @@ describe('Elements', () => {
});

test('allows a transition from null to a valid Stripe object', () => {
let stripeProp: any = null;
const wrapper = ({children}: any) => (
<Elements stripe={stripeProp}>{children}</Elements>
const TestComponent = () => {
const elements = useElements();

if (!elements) {
return null;
}

if (elements === mockElements) {
return <>expected</>;
}

throw new Error(`unexpected useElements value: ${elements}`);
};

const {container, rerender} = render(
<Elements stripe={null}>
<TestComponent />
</Elements>
);

const {result, rerender} = renderHook(() => useElements(), {wrapper});
expect(result.current).toBe(null);
expect(container).toBeEmpty();

stripeProp = mockStripe;
rerender();
expect(result.current).toBe(mockElements);
rerender(
<Elements stripe={mockStripe}>
<TestComponent />
</Elements>
);

expect(container).toHaveTextContent('expected');
});

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

test('allows a transition from null to a valid Promise', async () => {
let stripeProp: any = null;
const wrapper = ({children}: any) => (
<Elements stripe={stripeProp}>{children}</Elements>
);
const TestComponent = () => {
const elements = useElements();

const {result, rerender, waitForNextUpdate} = renderHook(
() => useElements(),
{wrapper}
if (!elements) {
return null;
}

if (elements === mockElements) {
return <>expected</>;
}

throw new Error(`unexpected useElements value: ${elements}`);
};

const {container, rerender, findByText} = render(
<Elements stripe={null}>
<TestComponent />
</Elements>
);
expect(result.current).toBe(null);

stripeProp = mockStripePromise;
rerender();
expect(result.current).toBe(null);
expect(container).toBeEmpty();

await waitForNextUpdate();
rerender(
<Elements stripe={mockStripePromise}>
<TestComponent />
</Elements>
);

expect(result.current).toBe(mockElements);
expect(container).toBeEmpty();

await findByText('expected');
});

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

0 comments on commit dc99847

Please sign in to comment.