Mirror: The highly customizable and versatile GraphQL client with which you add on features like normalized caching as you grow.
at main 2.9 kB view raw
1import { formatDocument, gql } from '@urql/core'; 2import { describe, it, expect } from 'vitest'; 3import { getMainOperation } from './traversal'; 4import { normalizeVariables, filterVariables } from './variables'; 5 6describe('normalizeVariables', () => { 7 it('normalizes variables', () => { 8 const input = { x: 42 }; 9 const operation = getMainOperation( 10 formatDocument(gql` 11 query ($x: Int!) { 12 field 13 } 14 `) 15 ); 16 const normalized = normalizeVariables(operation, input); 17 expect(normalized).toEqual({ x: 42 }); 18 }); 19 20 it('normalizes variables with defaults', () => { 21 const input = { x: undefined }; 22 const operation = getMainOperation( 23 formatDocument(gql` 24 query ($x: Int! = 42) { 25 field 26 } 27 `) 28 ); 29 const normalized = normalizeVariables(operation, input); 30 expect(normalized).toEqual({ x: 42 }); 31 }); 32 33 it('normalizes variables even with missing fields', () => { 34 const input = { x: undefined }; 35 const operation = getMainOperation( 36 formatDocument(gql` 37 query ($x: Int!) { 38 field 39 } 40 `) 41 ); 42 const normalized = normalizeVariables(operation, input); 43 expect(normalized).toEqual({}); 44 }); 45 46 it('skips normalizing for queries without variables', () => { 47 const operation = getMainOperation( 48 formatDocument(gql` 49 query { 50 field 51 } 52 `) 53 ); 54 (operation as any).variableDefinitions = undefined; 55 const normalized = normalizeVariables(operation, {}); 56 expect(normalized).toEqual({}); 57 }); 58 59 it('preserves missing variables', () => { 60 const operation = getMainOperation( 61 formatDocument(gql` 62 query { 63 field 64 } 65 `) 66 ); 67 (operation as any).variableDefinitions = undefined; 68 const normalized = normalizeVariables(operation, { test: true }); 69 expect(normalized).toEqual({ test: true }); 70 }); 71}); 72 73describe('filterVariables', () => { 74 it('returns undefined when no variables are defined', () => { 75 const operation = getMainOperation( 76 formatDocument(gql` 77 query { 78 field 79 } 80 `) 81 ); 82 const vars = filterVariables(operation, { test: true }); 83 expect(vars).toBe(undefined); 84 }); 85 86 it('filters out missing vars', () => { 87 const input = { x: true, y: false }; 88 const operation = getMainOperation( 89 formatDocument(gql` 90 query ($x: Int!) { 91 field 92 } 93 `) 94 ); 95 const vars = filterVariables(operation, input); 96 expect(vars).toEqual({ x: true }); 97 }); 98 99 it('ignores defaults', () => { 100 const input = { x: undefined }; 101 const operation = getMainOperation( 102 formatDocument(gql` 103 query ($x: Int! = 42) { 104 field 105 } 106 `) 107 ); 108 const vars = filterVariables(operation, input); 109 expect(vars).toEqual({ x: undefined }); 110 }); 111});