Skip to content

Commit

Permalink
add tests for useProfile and usePublication
Browse files Browse the repository at this point in the history
  • Loading branch information
krzysu committed Oct 4, 2023
1 parent f31c4e8 commit 8e77d42
Show file tree
Hide file tree
Showing 9 changed files with 281 additions and 6 deletions.
53 changes: 53 additions & 0 deletions packages/api-bindings/src/apollo/cache/createProfileFieldPolicy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
defaultDataIdFromObject,
FieldFunctionOptions,
FieldPolicy,
Reference,
StoreObject,
} from '@apollo/client';
import { never } from '@lens-protocol/shared-kernel';

import { Profile, ProfileRequest } from '../../lens';

function isProfile(value: StoreObject | undefined): value is Profile {
return value?.__typename === 'Profile';
}

const identifierPattern =
defaultDataIdFromObject({ __typename: 'Profile', id: '0x[a-fA-F0-9]{2,}' }) ?? never();
const identifierMatcher = new RegExp(`^${identifierPattern}$`);

export function createProfileFieldPolicy(): FieldPolicy<
Profile,
Profile,
Reference,
FieldFunctionOptions<{ request: ProfileRequest }>
> {
return {
keyArgs: [['request', ['forProfileId', 'forHandle']]],

read(_, { args, toReference, cache }) {
if (args?.request.forProfileId) {
return toReference({
__typename: 'Profile',
id: args.request.forProfileId,
});
}

const normalizedCacheObject = cache.extract(true);

for (const key in normalizedCacheObject) {
const value = normalizedCacheObject[key];

if (
identifierMatcher.test(key) &&
isProfile(value) &&
value.handle === args?.request.forHandle
) {
return toReference(value);
}
}
return;
},
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { StrictTypedTypePolicies } from '../../lens';

export function createProfileTypePolicy(): StrictTypedTypePolicies['Profile'] {
return {
fields: {},
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { FieldFunctionOptions, FieldPolicy, Reference } from '@apollo/client';

import { AnyPublication, PublicationRequest } from '../../lens';

export function createPublicationFieldPolicy(): FieldPolicy<
AnyPublication,
AnyPublication,
Reference,
FieldFunctionOptions<{ request: PublicationRequest }>
> {
return {
keyArgs: [['request', ['forId', 'forHandle']]],

read(_, { args, toReference }) {
if (args?.request.forId) {
return toReference({
__typename: 'Publication',
id: args.request.forId,
});
}

return;
},
};
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { StoreObject } from '@apollo/client';

const publicationTypename = 'Publication';

export function createPublicationTypePolicy() {
return {
keyFields: ({ id }: Readonly<StoreObject>) => `${publicationTypename}:${String(id)}`,
keyFields: ({ id }: Readonly<StoreObject>) => `Publication:${String(id)}`,
} as const;
}
10 changes: 8 additions & 2 deletions packages/api-bindings/src/apollo/cache/createTypePolicies.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { TypePolicy } from '@apollo/client';
import { FieldPolicy, TypePolicy } from '@apollo/client';

import { StrictTypedTypePolicies } from '../../lens';
import { createProfileFieldPolicy } from './createProfileFieldPolicy';
import { createProfileTypePolicy } from './createProfileTypePolicy';
import { createProfilesFieldPolicy } from './createProfilesFieldPolicy';
import { createPublicationFieldPolicy } from './createPublicationFieldPolicy';
import { createPublicationTypePolicy } from './createPublicationTypePolicy';
import { createPublicationsFieldPolicy } from './createPublicationsFieldPolicy';
import { notNormalizedType } from './utils/notNormalizedType';
Expand All @@ -12,6 +15,7 @@ type InheritedTypePolicies = {

export function createTypePolicies(): StrictTypedTypePolicies & InheritedTypePolicies {
return {
Profile: createProfileTypePolicy(),
Publication: createPublicationTypePolicy(),
Post: notNormalizedType(),
Comment: notNormalizedType(),
Expand All @@ -22,8 +26,10 @@ export function createTypePolicies(): StrictTypedTypePolicies & InheritedTypePol

Query: {
fields: {
publications: createPublicationsFieldPolicy(),
profile: createProfileFieldPolicy() as FieldPolicy<unknown>,
profiles: createProfilesFieldPolicy(),
publication: createPublicationFieldPolicy() as FieldPolicy<unknown>,
publications: createPublicationsFieldPolicy(),
},
},
};
Expand Down
23 changes: 23 additions & 0 deletions packages/api-bindings/src/lens/__helpers__/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import {
ProfilesData,
ProfilesDocument,
ProfilesVariables,
ProfileData,
ProfileDocument,
ProfileVariables,
PublicationData,
PublicationDocument,
PublicationVariables,
Expand Down Expand Up @@ -42,6 +45,26 @@ export function mockPublicationResponse({
};
}

export function mockProfileResponse({
variables,
profile,
}: {
variables: ProfileVariables;
profile: Profile | null;
}): MockedResponse<ProfileData> {
return {
request: {
query: ProfileDocument,
variables,
},
result: {
data: {
result: profile,
},
},
};
}

export function mockPublicationsResponse({
variables,
publications,
Expand Down
2 changes: 1 addition & 1 deletion packages/react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"lint:fix": "pnpm run prettier:fix && pnpm run eslint:fix && pnpm run tsc",
"prettier:fix": "prettier --write .",
"prettier": "prettier --check .",
"test": "exit 0",
"test": "jest",
"test:watch": "jest --watch",
"tsc": "tsc --noEmit"
},
Expand Down
79 changes: 79 additions & 0 deletions packages/react/src/profile/__tests__/useProfile.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { Profile } from '@lens-protocol/api-bindings';
import {
mockLensApolloClient,
mockProfileResponse,
mockProfileFragment,
simulateNotAuthenticated,
} from '@lens-protocol/api-bindings/mocks';
import { waitFor } from '@testing-library/react';

import { NotFoundError } from '../../NotFoundError';
import { renderHookWithMocks } from '../../__helpers__/testing-library';
import {
defaultMediaTransformsConfig,
mediaTransformConfigToQueryVariables,
} from '../../mediaTransforms';
import { useProfile, UseProfileArgs } from '../useProfile';

function setupTestScenario({ profile, ...args }: UseProfileArgs & { profile: Profile | null }) {
return renderHookWithMocks(() => useProfile(args), {
mocks: {
mediaTransforms: defaultMediaTransformsConfig,
apolloClient: mockLensApolloClient([
mockProfileResponse({
profile,
variables: {
request: args.forProfileId
? {
forProfileId: args.forProfileId,
}
: {
forHandle: args.forHandle,
},
...mediaTransformConfigToQueryVariables(defaultMediaTransformsConfig),
},
}),
]),
},
});
}

describe(`Given the ${useProfile.name} hook`, () => {
const profile = mockProfileFragment();
const expectations = { __typename: 'Profile', id: profile.id };

beforeAll(() => {
simulateNotAuthenticated();
});

describe.each([
{
description: 'when invoked with a profile id',
args: { forProfileId: profile.id },
},
{
description: 'when invoked with a profile handle',
args: { forHandle: profile.handle },
},
])('$description', ({ args }) => {
it('should settle with the profile data', async () => {
const { result } = setupTestScenario({
...args,
profile,
});

await waitFor(() => expect(result.current.loading).toBeFalsy());
expect(result.current.data).toMatchObject(expectations);
});

it(`should settle with a ${NotFoundError.name} if not found`, async () => {
const { result } = setupTestScenario({
...args,
profile: null,
});

await waitFor(() => expect(result.current.loading).toBeFalsy());
expect(result.current.error).toBeInstanceOf(NotFoundError);
});
});
});
84 changes: 84 additions & 0 deletions packages/react/src/publication/__tests__/usePublication.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { MockedResponse } from '@apollo/client/testing';
import {
mockLensApolloClient,
mockPostFragment,
mockPublicationResponse,
simulateNotAuthenticated,
} from '@lens-protocol/api-bindings/mocks';
import { RenderHookResult, waitFor } from '@testing-library/react';

import { NotFoundError } from '../../NotFoundError';
import { renderHookWithMocks } from '../../__helpers__/testing-library';
import {
defaultMediaTransformsConfig,
mediaTransformConfigToQueryVariables,
} from '../../mediaTransforms';
import { usePublication } from '../usePublication';

function setupTestScenario(mocks: MockedResponse[]) {
const client = mockLensApolloClient(mocks);

return {
renderHook<TProps, TResult>(
callback: (props: TProps) => TResult,
): RenderHookResult<TResult, TProps> {
return renderHookWithMocks(callback, {
mocks: {
mediaTransforms: defaultMediaTransformsConfig,
apolloClient: client,
},
});
},
};
}

describe(`Given the ${usePublication.name} hook`, () => {
const publication = mockPostFragment();
const expectations = { __typename: 'Post', id: publication.id };

beforeAll(() => {
simulateNotAuthenticated();
});

describe('when the queried publication exists', () => {
const { renderHook } = setupTestScenario([
mockPublicationResponse({
variables: {
request: {
forId: publication.id,
},
...mediaTransformConfigToQueryVariables(defaultMediaTransformsConfig),
},
publication,
}),
]);

it('should settle with the publication data', async () => {
const { result } = renderHook(() => usePublication({ forId: publication.id }));

await waitFor(() => expect(result.current.loading).toBeFalsy());
expect(result.current.data).toMatchObject(expectations);
});
});

describe('when the queried publication does not exist', () => {
const { renderHook } = setupTestScenario([
mockPublicationResponse({
variables: {
request: {
forId: publication.id,
},
...mediaTransformConfigToQueryVariables(defaultMediaTransformsConfig),
},
publication: null,
}),
]);

it(`should settle with a ${NotFoundError.name} state`, async () => {
const { result } = renderHook(() => usePublication({ forId: publication.id }));

await waitFor(() => expect(result.current.loading).toBeFalsy());
expect(result.current.error).toBeInstanceOf(NotFoundError);
});
});
});

0 comments on commit 8e77d42

Please sign in to comment.