import {RequestParameters, GraphQLResponse} from 'relay-runtime'; import fetchMock from 'fetch-mock'; // FIXME: imports in this manner work fine via `yarn test` but fails in-editor // for code completion, but this is likely a local misconfiguration import environment, {cache, fetchQuery} from 'packs/frontend/graphqlEnvironment'; //import environment, {cache, fetchQuery} from '../../../app/javascript/packs/frontend/graphqlEnvironment'; describe('fetchQuery', () => { const defaultRequestParameters: RequestParameters = { name: 'test query', operationKind: 'query', metadata: {foo: 'bar'}, id: null, text: 'dummy text', }; afterEach(fetchMock.reset); it('builds the correct request', done => { fetchMock.mock('/api/graphql', {great: 'success', errors: []}); const res = fetchQuery(defaultRequestParameters, {bar: 'baz'}, null); const opts = fetchMock.lastOptions(); expect(opts.method).toEqual('POST'); expect(opts.headers['Content-Type']).toEqual('application/json'); expect(opts['body']).toEqual(JSON.stringify({query: 'dummy text', variables: {bar: 'baz'}})); (res as Promise).finally(() => { cache.clear(); done(); }); }); it('responds with json', done => { fetchMock.mock('/api/graphql', {great: 'success', errors: []}); const res = fetchQuery(defaultRequestParameters, {bar: 'baz'}, null); (res as Promise) .then(data => expect(data).toEqual({great: 'success', errors: []})) .finally(() => { cache.clear(); done(); }); }); it('caches responses', done => { const variables = {bar: 'baz'}; const expectedResponse = {great: 'success', errors: []}; cache.set(defaultRequestParameters.name, variables, expectedResponse); fetchMock.postOnce('/api/graphql', {great: 'success 1', errors: []}); const res = fetchQuery(defaultRequestParameters, variables, null); expect(fetchMock.calls().length).toEqual(0); (res as Promise) .then(data => { expect(data.extensions).not.toBeNull(); expect(data.extensions.cacheTimestamp).not.toBeNull(); // Remove cache data from response info after we've verified it exists delete data.extensions; expect(data).toEqual(expectedResponse); }) .finally(() => { cache.clear(); done(); }); }); it('bypasses cache when force param given', done => { const variables = {bar: 'baz'}; const cachedResponse = {great: 'success', errors: []}; cache.set(defaultRequestParameters.name, variables, cachedResponse); fetchMock.postOnce('/api/graphql', {great: 'success 1', errors: []}); const res = fetchQuery(defaultRequestParameters, variables, {force: true}); expect(fetchMock.calls().length).toEqual(1); (res as Promise) .then(data => expect(data).toEqual({great: 'success 1', errors: []})) .finally(() => { cache.clear(); done(); }); }); });