Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: React package tests #1054

Merged
merged 1 commit into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/verify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,4 @@ jobs:
echo "TEST_ACCOUNT=${{ vars.TEST_ACCOUNT }}" >> .env

- name: Run Tests
run: pnpm test:storage && pnpm test:client
run: pnpm test
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ The official SDK for the Lens 🌿.

- [Installation](#installation)
- [Development Workflow](#development-workflow)
- [Troubleshooting](#troubleshooting)
- [Contributing](#contributing)
- [License](#license)

Expand Down Expand Up @@ -113,6 +114,40 @@ The project uses [Biome](https://biomejs.dev/) to format and lint the code. You

9. Merge the pull request to the `main` branch.

## Troubleshooting

### Incompatible Types Across Packages <!-- omit in toc -->

Working within a monorepo can sometimes lead to type incompatibilities across packages. If you encounter an error like:

```bash
Type 'import("[...]/packages/client/dist/index").PublicClient<import("[...]/packages/client/dist/index").Context>' is not assignable to type 'import("[...]/packages/client/src/clients").PublicClient<import("[...]/packages/client/src/context").Context>'.
```

This usually indicates that TypeScript is picking up types from different versions of the same package. To resolve this, make sure you have configured the entry points correctly as aliases in the top level `tsconfig.json` file.

```json
{
"$schema": "https://json.schemastore.org/tsconfig",
"compilerOptions": {
"skipLibCheck": true,
"types": ["node"],
"paths": {
"@lens-protocol/client": ["./packages/client/src"],
"@lens-protocol/client/actions": ["./packages/client/src/actions"],
"@lens-protocol/client/test-utils": ["./packages/client/src/test-utils"],
"@lens-protocol/env": ["./packages/env/src"],
"@lens-protocol/graphql": ["./packages/graphql/src"],
"@lens-protocol/react": ["./packages/react/src"],
"@lens-protocol/storage": ["./packages/storage/src"],
"@lens-protocol/types": ["./packages/types/src"]
}
},
"include": ["**/*.ts"],
"exclude": ["dist", "node_modules"]
}
```

## Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
Expand Down
8 changes: 7 additions & 1 deletion packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,19 @@
"import": "./dist/viem/index.js",
"require": "./dist/viem/index.cjs",
"types": "./dist/viem/index.d.cts"
},
"./test-utils": {
"import": "./dist/test-utils.js",
"require": "./dist/test-utils.cjs",
"types": "./dist/test-utils.d.cts"
}
},
"typesVersions": {
"*": {
"actions": ["./dist/actions/index.d.ts"],
"ethers": ["./dist/ethers/index.d.ts"],
"viem": ["./dist/viem/index.d.ts"]
"viem": ["./dist/viem/index.d.ts"],
"test-utils": ["./dist/test-utils.d.ts"]
}
},
"files": ["dist"],
Expand Down
7 changes: 3 additions & 4 deletions packages/client/src/actions/accountManager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { beforeAll, describe, expect, it } from 'vitest';
import { type Account, assertTypename } from '@lens-protocol/graphql';
import * as metadata from '@lens-protocol/metadata';
import { assertOk, never, uri } from '@lens-protocol/types';
import { loginAsOnboardingUser, signerWallet, storageClient } from '../../testing-utils';
import type { SessionClient } from '../clients';
import { loginAsOnboardingUser, storageClient, wallet } from '../test-utils';
import { handleWith } from '../viem';
import {
createAccountWithUsername,
Expand All @@ -14,7 +14,6 @@ import {
} from './account';
import { fetchMeDetails } from './authentication';

const walletClient = signerWallet();
describe('Given a new Lens Account', () => {
let newAccount: Account;
let sessionClient: SessionClient;
Expand All @@ -28,7 +27,7 @@ describe('Given a new Lens Account', () => {
username: { localName: `testname${Date.now()}` },
metadataUri: uri(`data:application/json,${JSON.stringify(initialMetadata)}`), // empty at first
})
.andThen(handleWith(walletClient))
.andThen(handleWith(wallet))
.andThen(sessionClient.waitForTransaction)
.andThen((txHash) => fetchAccount(sessionClient, { txHash }))
.andThen((account) => {
Expand All @@ -47,7 +46,7 @@ describe('Given a new Lens Account', () => {
describe(`When invoking the '${enableSignless.name}' action`, () => {
beforeAll(async () => {
const result = await enableSignless(sessionClient)
.andThen(handleWith(walletClient))
.andThen(handleWith(wallet))
.andThen(sessionClient.waitForTransaction);
assertOk(result);
});
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/actions/notifications.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { assertOk } from '@lens-protocol/types';
import { describe, it } from 'vitest';

import { loginAsAccountOwner } from '../../testing-utils';
import { loginAsAccountOwner } from '../test-utils';
import { fetchNotifications } from './notifications';

describe(`Given the '${fetchNotifications.name}' action`, () => {
Expand Down
5 changes: 2 additions & 3 deletions packages/client/src/actions/onboarding.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@ import { describe, expect, it } from 'vitest';

import { type Account, Role } from '@lens-protocol/graphql';
import { uri } from '@lens-protocol/types';
import { loginAsOnboardingUser, signer, signerWallet } from '../../testing-utils';
import { loginAsOnboardingUser, signer, wallet } from '../test-utils';
import { handleWith } from '../viem';
import { createAccountWithUsername, fetchAccount } from './account';

const walletClient = signerWallet();
const metadata = account({
name: 'John Doe',
bio: 'A test account',
Expand All @@ -27,7 +26,7 @@ describe('Given an onboarding user', () => {
metadataUri: uri(`data:application/json,${JSON.stringify(metadata)}`),
})
// Sign if necessary
.andThen(handleWith(walletClient))
.andThen(handleWith(wallet))

// Wait for the transaction to be mined
.andThen(sessionClient.waitForTransaction)
Expand Down
2 changes: 1 addition & 1 deletion packages/client/src/clients.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import { privateKeyToAccount } from 'viem/accounts';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';

import { CurrentSessionQuery, HealthQuery, RefreshMutation, Role } from '@lens-protocol/graphql';
import { createGraphQLErrorObject, createPublicClient } from '../testing-utils';
import { currentSession } from './actions';
import { PublicClient } from './clients';
import { GraphQLErrorCode, UnauthenticatedError, UnexpectedError } from './errors';
import { createGraphQLErrorObject, createPublicClient } from './test-utils';
import { delay } from './utils';

const signer = privateKeyToAccount(import.meta.env.PRIVATE_KEY);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
/// <reference path="../../../vite-env.d.ts" />

import { chains } from '@lens-network/sdk/viem';
import { StorageClient, testnet as storageEnv } from '@lens-protocol/storage-node-client';
import { evmAddress } from '@lens-protocol/types';
import { http, type Account, type Transport, type WalletClient, createWalletClient } from 'viem';
import { privateKeyToAccount } from 'viem/accounts';

import { GraphQLErrorCode, PublicClient, testnet as apiEnv } from './src';
import { GraphQLErrorCode, PublicClient, testnet as apiEnv } from '.';

const pk = privateKeyToAccount(import.meta.env.PRIVATE_KEY);
const account = evmAddress(import.meta.env.TEST_ACCOUNT);
const app = evmAddress(import.meta.env.TEST_APP);

export const signer = evmAddress(pk.address);
export const account = evmAddress(import.meta.env.TEST_ACCOUNT);
export const app = evmAddress(import.meta.env.TEST_APP);
export const wallet: WalletClient<Transport, chains.LensNetworkChain, Account> = createWalletClient(
{
account: pk,
chain: chains.testnet,
transport: http(),
},
);
export const signer = evmAddress(wallet.account.address);

export function createPublicClient() {
return PublicClient.create({
Expand Down Expand Up @@ -44,14 +52,6 @@ export function loginAsOnboardingUser() {
});
}

export function signerWallet(): WalletClient<Transport, chains.LensNetworkChain, Account> {
return createWalletClient({
account: privateKeyToAccount(import.meta.env.PRIVATE_KEY),
chain: chains.testnet,
transport: http(),
});
}

const messages: Record<GraphQLErrorCode, string> = {
[GraphQLErrorCode.UNAUTHENTICATED]:
"Unauthenticated - Authentication is required to access '<operation>'",
Expand Down
8 changes: 7 additions & 1 deletion packages/client/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,13 @@
import { defineConfig } from 'tsup';

export default defineConfig(() => ({
entry: ['src/index.ts', 'src/actions/index.ts', 'src/ethers/index.ts', 'src/viem/index.ts'],
entry: [
'src/index.ts',
'src/actions/index.ts',
'src/ethers/index.ts',
'src/viem/index.ts',
'src/test-utils.ts',
],
outDir: 'dist',
splitting: false,
sourcemap: true,
Expand Down
19 changes: 5 additions & 14 deletions packages/react/src/authentication/useLogin.test.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,12 @@
import { PublicClient } from '@lens-protocol/client';
import { local } from '@lens-protocol/env';
import { assertOk, evmAddress } from '@lens-protocol/types';
import { privateKeyToAccount } from 'viem/accounts';
import { assertOk } from '@lens-protocol/types';
import { describe, expect, it } from 'vitest';

import { account, app, createPublicClient, signer, wallet } from '@lens-protocol/client/test-utils';
import { renderHookWithContext } from '../__helpers__/testing-utils';
import { useLogin } from './useLogin';

const signer = privateKeyToAccount(import.meta.env.PRIVATE_KEY);
const account = evmAddress(signer.address);
const app = evmAddress(import.meta.env.TEST_APP);

describe(`Given the ${useLogin.name} hook`, () => {
const client = PublicClient.create({
environment: local,
origin: 'http://example.com',
});
const client = createPublicClient();

describe('When used to login into an existing Account', () => {
it('Then it should return the Account data', async () => {
Expand All @@ -27,8 +18,8 @@ describe(`Given the ${useLogin.name} hook`, () => {
account,
app,
signer: {
address: account,
signMessage: async (message: string) => signer.signMessage({ message }),
address: signer,
signMessage: async (message: string) => wallet.signMessage({ message }),
},
});

Expand Down
3 changes: 1 addition & 2 deletions packages/react/src/authentication/useLogin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ export function useLogin(): UseAsyncTask<LoginArgs, Account, LoginError> {
fetchAccount(sessionClient, { address: args.account }).andThen((account) => {
if (account === null) {
return AuthenticationError.from(
'Unable to retrieve the Account data you signed in with. ' +
'Please contact the Lens team.',
'Account not found. This could be a Lens API issue. Please report this to the Lens team.',
).asResultAsync();
}
return okAsync(account);
Expand Down
18 changes: 5 additions & 13 deletions packages/react/src/authentication/useSessionClient.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { local } from '@lens-protocol/env';
import { evmAddress } from '@lens-protocol/types';
import { privateKeyToAccount } from 'viem/accounts';

import { PublicClient, type SessionClient } from '@lens-protocol/client';
import type { SessionClient } from '@lens-protocol/client';
import { createPublicClient } from '@lens-protocol/client/test-utils';
import { beforeAll, describe, expect, it, vi } from 'vitest';
import { renderHookWithContext } from '../__helpers__/testing-utils';
import { useSessionClient } from './useSessionClient';
Expand All @@ -11,14 +11,10 @@ const signer = privateKeyToAccount(import.meta.env.PRIVATE_KEY);
const owner = evmAddress(signer.address);
const app = evmAddress(import.meta.env.TEST_APP);
const account = evmAddress(import.meta.env.TEST_ACCOUNT);
const client = createPublicClient();

describe(`Given the '${useSessionClient.name}' hook`, () => {
describe('And the user is not authenticated', () => {
const client = PublicClient.create({
environment: local,
origin: 'http://example.com',
});

describe('When rendered in traditional non-suspense mode', () => {
it('Then it should return `null`', async () => {
const { result } = renderHookWithContext(() => useSessionClient(), {
Expand All @@ -43,10 +39,6 @@ describe(`Given the '${useSessionClient.name}' hook`, () => {
});

describe('And the user is authenticated', () => {
const client = PublicClient.create({
environment: local,
origin: 'http://example.com',
});
let sessionClient: SessionClient;

beforeAll(async () => {
Expand All @@ -70,7 +62,7 @@ describe(`Given the '${useSessionClient.name}' hook`, () => {
});

await vi.waitUntil(() => result.current.loading === false);
expect(result.current.data?.getCredentials()).resolves.toEqual(credentials);
await expect(result.current.data?.getCredentials()).resolves.toEqual(credentials);
});

describe('When rendered in suspense mode', () => {
Expand All @@ -84,7 +76,7 @@ describe(`Given the '${useSessionClient.name}' hook`, () => {
});

await vi.waitUntil(() => result.current !== null);
expect(result.current.data?.getCredentials()).resolves.toEqual(credentials);
await expect(result.current.data?.getCredentials()).resolves.toEqual(credentials);
});
});
});
Expand Down
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"paths": {
"@lens-protocol/client": ["./packages/client/src"],
"@lens-protocol/client/actions": ["./packages/client/src/actions"],
"@lens-protocol/client/test-utils": ["./packages/client/src/test-utils"],
"@lens-protocol/env": ["./packages/env/src"],
"@lens-protocol/graphql": ["./packages/graphql/src"],
"@lens-protocol/react": ["./packages/react/src"],
Expand Down
Loading