All files / test accessor.tsx

94.11% Statements 32/34
100% Branches 3/3
84.61% Functions 11/13
93.54% Lines 29/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 1683x 3x 3x           3x 3x                                                         3x 9x   24x         9x               3x                                               11x               59x   5x     5x     5x   5x           31x     31x     31x 12x     19x     2x 2x                                                               3x 9x     13x   13x     12x               9x    
import { render } from '@testing-library/react/pure';
import React, { FunctionComponent, ReactNode, Suspense } from 'react';
import { useErrorBoundary } from 'use-error-boundary';
import {
  AccessorQueryCacheStore,
  AccessorQueryConfiguration,
  AccessorQueryResultCacheSetResult,
} from '../src/query';
import { createCache } from '../src/query/create_cache';
import { create as createPromise } from './promise_manual';
 
export type Book = {
  id: string;
  title: string;
  authorId: string;
};
 
export type Response<T> = {
  status: number;
  data?: T | null | undefined;
  error?: string | undefined;
};
 
export type RequestBook = {
  id: string;
};
 
export type ResponseBook = {
  book: Book;
};
 
export interface CacheStore extends AccessorQueryCacheStore {
  books: Map<string, Book>;
}
 
/*
 * Creates a cache store.
 */
export const createCacheStore = (): CacheStore => {
  const cacheStore = {
    ...createCache(setter => {
      setter(cacheStore);
    }),
    books: new Map<string, Book>(),
  };
 
  return cacheStore;
};
 
/*
 * Create an accessor query configuration.
 *
 * Parts of the configuration can be overwritten when provided as arguments.
 */
export const createQueryConfiguration = (overrides: {
  cache?: Partial<
    AccessorQueryConfiguration<
      CacheStore,
      RequestBook,
      ResponseBook,
      Book
    >['cache']
  >;
  constraints?: Partial<
    AccessorQueryConfiguration<
      CacheStore,
      RequestBook,
      ResponseBook,
      Book
    >['constraints']
  >;
  query?: AccessorQueryConfiguration<
    CacheStore,
    RequestBook,
    ResponseBook,
    Book
  >['query'];
}): AccessorQueryConfiguration<CacheStore, RequestBook, ResponseBook, Book> => {
  return {
    debug: false,
    constraints: {
      ...overrides.constraints,
    },
    cache: {
      duration: 1000 * 60, // 1min
      isPrimableFromCache: true,
      id: ({ args }) => `getBook#id#${args.id}`,
      set: ({ cache, response }): { data: Book } => {
        const store = cache();
 
        // Parse.
        const book = response.data.book;
 
        // Set cache.
        store.books.set(book.id, book);
 
        return { data: book };
      },
      get: ({
        cache,
        args,
      }): AccessorQueryResultCacheSetResult<Book> | null => {
        const store = cache();
 
        // Get cache.
        const cacheResult = store.books.get(args.id);
 
        // Do we have a cache result?
        if (typeof cacheResult !== 'undefined') {
          return { data: cacheResult };
        }
 
        return null;
      },
      clear: ({ args, set }): void => {
        set(({ books }) => {
          books.delete(args.id);
        });
      },
      ...overrides.cache,
    } as AccessorQueryConfiguration<
      CacheStore,
      RequestBook,
      ResponseBook,
      Book
    >['cache'],
    query: overrides.query
      ? (overrides.query as AccessorQueryConfiguration<
          CacheStore,
          RequestBook,
          ResponseBook,
          Book
        >['query'])
      : async (args: RequestBook): Promise<Response<ResponseBook>> => {
          return createPromise<Response<ResponseBook>>(
            { resolve: true },
            {
              status: 200,
              data: { book: { id: args.id, title: 'My Book', authorId: '3' } },
            },
          );
        },
  };
};
 
/*
 * Render a self contained accessor with an error boundary and suspense baked in.
 */
export const renderAccessor = (component: ReactNode) => {
  const AccessorDependencies: FunctionComponent<{ children: ReactNode }> = ({
    children,
  }) => {
    const { ErrorBoundary } = useErrorBoundary();
 
    return (
      <ErrorBoundary
        renderError={({ error }) => (
          <span>{`${error.message} ${error.stack}`}</span>
        )}
      >
        <Suspense fallback={<span>Loading...</span>}>{children}</Suspense>
      </ErrorBoundary>
    );
  };
 
  return render(<AccessorDependencies>{component}</AccessorDependencies>);
};