From e1885d7a7246cf5f6436011f0600d8d03decbe39 Mon Sep 17 00:00:00 2001 From: Ben Newman Date: Fri, 20 Aug 2021 12:29:23 -0400 Subject: [PATCH] Test `key: ["$variable"]` field policies. --- src/cache/inmemory/__tests__/policies.ts | 100 +++++++++++++++++++++++ 1 file changed, 100 insertions(+) diff --git a/src/cache/inmemory/__tests__/policies.ts b/src/cache/inmemory/__tests__/policies.ts index 55d7a92756b..8692144d45e 100644 --- a/src/cache/inmemory/__tests__/policies.ts +++ b/src/cache/inmemory/__tests__/policies.ts @@ -1274,6 +1274,106 @@ describe("type policies", function () { }); })); + it("can refer to variables in field key shorthand array", function () { + const cache = new InMemoryCache({ + typePolicies: { + Query: { + fields: { + defaultToNumVariable: { + key: ["input", "$num"], + read(existing, { args, variables }) { + return existing ?? args?.input ?? variables?.num; + }, + }, + }, + }, + }, + }); + + const queryWithInputArg = gql` + query WithInputArg($num: Int) { + defaultToNumVariable(input: 1234) + } + `; + + cache.writeQuery({ + query: queryWithInputArg, + data: { + defaultToNumVariable: "forced with input and $num", + }, + variables: { + num: 1234, + }, + }); + + expect(cache.extract()).toEqual({ + ROOT_QUERY: { + "__typename": "Query", + 'defaultToNumVariable:{"input":1234,"$num":1234}': "forced with input and $num", + }, + }); + + const queryWithNoArgs = gql` + query WithInputArg($num: Int) { + defaultToNumVariable + } + `; + + cache.writeQuery({ + query: queryWithNoArgs, + data: { + defaultToNumVariable: "forced with only $num", + }, + variables: { + num: 2345, + }, + }); + + expect(cache.extract()).toEqual({ + ROOT_QUERY: { + "__typename": "Query", + 'defaultToNumVariable:{"input":1234,"$num":1234}': "forced with input and $num", + 'defaultToNumVariable:{"$num":2345}': "forced with only $num", + }, + }); + + expect(cache.readQuery({ + query: queryWithInputArg, + variables: { + num: 1234, + }, + })).toEqual({ + defaultToNumVariable: "forced with input and $num", + }); + + expect(cache.readQuery({ + query: queryWithNoArgs, + variables: { + num: 2345, + }, + })).toEqual({ + defaultToNumVariable: "forced with only $num", + }); + + expect(cache.readQuery({ + query: queryWithInputArg, + variables: { + num: 3456, + }, + })).toEqual({ + defaultToNumVariable: 1234, + }); + + expect(cache.readQuery({ + query: queryWithNoArgs, + variables: { + num: 4567, + }, + })).toEqual({ + defaultToNumVariable: 4567, + }); + }); + it("can use options.storage in read functions", function () { const storageSet = new Set>();