From b4303c0d952c7fa9d1eb42693b24ae7e36eda455 Mon Sep 17 00:00:00 2001 From: Martin Huschenbett Date: Mon, 24 Feb 2020 11:03:27 +0100 Subject: [PATCH] @daml/react: Add rerendering test for useQuery Add a test for `useQuery` that ensure that we don't call the JSON API if the component calling the hook changes without changing the query. CHANGELOG_BEGIN CHANGELOG_END --- language-support/ts/daml-react/hooks.test.ts | 24 ++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/language-support/ts/daml-react/hooks.test.ts b/language-support/ts/daml-react/hooks.test.ts index 748216370871..179916d15660 100644 --- a/language-support/ts/daml-react/hooks.test.ts +++ b/language-support/ts/daml-react/hooks.test.ts @@ -69,6 +69,7 @@ describe('useQuery', () => { const resolvent1 = ['foo']; const resolvent2 = ['bar']; + // First rendering works? mockQuery.mockReturnValueOnce(Promise.resolve(resolvent1)); const {result, waitForNextUpdate} = renderDamlHook(() => { const [query, setQuery] = useState(query1); @@ -83,6 +84,7 @@ describe('useQuery', () => { await waitForNextUpdate(); expect(result.current.queryResult).toEqual({contracts: resolvent1, loading: false}); + // Change to query triggers another call to JSON API? mockQuery.mockReturnValueOnce(Promise.resolve(resolvent2)); act(() => result.current.setQuery(query2)); expect(mockQuery).toHaveBeenCalledTimes(1); @@ -93,4 +95,26 @@ describe('useQuery', () => { await waitForNextUpdate(); expect(result.current.queryResult).toEqual({contracts: resolvent2, loading: false}); }); + + test('rerendering without query change', async () => { + const query = 'query'; + const resolvent = ['foo']; + + // First rendering works? + mockQuery.mockReturnValueOnce(Promise.resolve(resolvent)); + const {result, waitForNextUpdate} = renderDamlHook(() => { + const setState = useState('state')[1]; + const queryResult = useQuery(Foo, () => ({query}), [query]); + return {queryResult, query, setState}; + }); + expect(mockQuery).toHaveBeenCalledTimes(1); + mockQuery.mockClear(); + await waitForNextUpdate(); + expect(result.current.queryResult).toEqual({contracts: resolvent, loading: false}); + + // Change to unrelated state does _not_ trigger another call to JSON API? + act(() => result.current.setState('new-state')); + expect(mockQuery).not.toHaveBeenCalled(); + expect(result.current.queryResult).toEqual({contracts: resolvent, loading: false}); + }); });