Skip to content

Commit

Permalink
feat: added optional wrappers around various libraries
Browse files Browse the repository at this point in the history
BREAKING CHANGE: Removed `useReadOnlyCachedState` and `useClassNames`
  • Loading branch information
cecilia-sanare committed Feb 22, 2024
1 parent b332250 commit ea6db18
Show file tree
Hide file tree
Showing 17 changed files with 167 additions and 92 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,26 @@ it('should ...', async () => {
});
```

### Built-Ins

We have a variety of wrappers for libraries built-in to simplify testing!

```tsx
import { HelmetProvider } from '@rain-cafe/react-utils/react-helmet-async';
import { QueryClientProvider } from '@rain-cafe/react-utils/react-query';
import { MemoryRouter } from '@rain-cafe/react-utils/react-router';

const KitchenSink = wrap.concat(HelmetProvider, QueryClientProvider, MemoryRouter);

it('should ...', async () => {
const Component = await KitchenSink(import('../MyComponent.tsx')));

render(<Component value="Hello world!" />);

// ...
});
```

[_**Want to Contribute?**_](/CONTRIBUTING.md)

[npm-version-image]: https://img.shields.io/npm/v/@rain-cafe/react-utils.svg
Expand Down
Binary file modified bun.lockb
Binary file not shown.
6 changes: 5 additions & 1 deletion jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ export default {
roots: ['<rootDir>/src'],
testEnvironment: '@happy-dom/jest-environment',

moduleNameMapper: {
'^@rain-cafe/react-utils$': '<rootDir>/src/index.ts',
},

coverageProvider: 'v8',

transform: {
Expand All @@ -16,6 +20,6 @@ export default {

collectCoverageFrom: ['<rootDir>/src/**/*'],
coveragePathIgnorePatterns: ['__tests__'],
setupFilesAfterEnv: ['@inrupt/jest-jsdom-polyfills', '@testing-library/jest-dom/extend-expect'],
setupFilesAfterEnv: ['@inrupt/jest-jsdom-polyfills', '@testing-library/jest-dom/matchers'],
extensionsToTreatAsEsm: ['.ts', '.tsx'],
} satisfies Config;
66 changes: 42 additions & 24 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,31 @@
"name": "@rain-cafe/react-utils",
"version": "1.0.0",
"type": "module",
"source": "src/index.ts",
"source": "src/*.ts",
"main": "./dist/index.cjs",
"module": "./dist/index.module.js",
"unpkg": "./dist/index.umd.js",
"exports": {
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts",
"default": "./dist/index.modern.js"
".": {
"require": "./dist/index.cjs",
"types": "./dist/index.d.ts",
"default": "./dist/index.modern.js"
},
"./react-router": {
"require": "./dist/tests/libs/react-router.cjs",
"types": "./dist/tests/libs/react-router.d.ts",
"default": "./dist/tests/libs/react-router.modern.js"
},
"./react-helmet-async": {
"require": "./dist/tests/libs/react-helmet-async.cjs",
"types": "./dist/tests/libs/react-helmet-async.d.ts",
"default": "./dist/tests/libs/react-helmet-async.modern.js"
},
"./react-query": {
"require": "./dist/tests/libs/react-query.cjs",
"types": "./dist/tests/libs/react-query.d.ts",
"default": "./dist/tests/libs/react-query.modern.js"
}
},
"types": "dist/index.d.ts",
"scripts": {
Expand All @@ -25,31 +42,32 @@
"classnames": "^2.5.1"
},
"devDependencies": {
"@happy-dom/jest-environment": "^13.0.6",
"@inrupt/jest-jsdom-polyfills": "^3.0.2",
"@swc/jest": "^0.2.29",
"@tanstack/react-query": "^5.20.5",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^14.0.0",
"@testing-library/user-event": "^14.4.3",
"@types/jest": "^29.5.3",
"@types/react": "^18.2.17",
"@typescript-eslint/eslint-plugin": "^6.2.1",
"@typescript-eslint/parser": "^6.2.1",
"@happy-dom/jest-environment": "^13.4.1",
"@inrupt/jest-jsdom-polyfills": "^3.2.0",
"@swc/jest": "^0.2.36",
"@tanstack/react-query": "^5.22.2",
"@testing-library/jest-dom": "^6.4.2",
"@testing-library/react": "^14.2.1",
"@testing-library/user-event": "^14.5.2",
"@types/jest": "^29.5.12",
"@types/react": "^18.2.57",
"@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^7.0.2",
"chance": "^1.1.11",
"eslint": "^8.46.0",
"eslint-config-prettier": "^8.9.0",
"eslint": "^8.56.0",
"eslint-config-prettier": "^9.1.0",
"eslint-config-react": "^1.1.7",
"eslint-plugin-react": "^7.33.1",
"eslint-plugin-unused-imports": "^3.0.0",
"jest": "^29.6.2",
"eslint-plugin-react": "^7.33.2",
"eslint-plugin-unused-imports": "^3.1.0",
"jest": "^29.7.0",
"microbundle": "^0.15.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.0",
"ts-jest": "^29.1.1",
"ts-node": "^10.9.1",
"typescript": "^5.1.6"
"react-helmet-async": "^2.0.4",
"react-router-dom": "^6.22.1",
"ts-jest": "^29.1.2",
"ts-node": "^10.9.2",
"typescript": "^5.3.3"
},
"publishConfig": {
"access": "public"
Expand Down
46 changes: 1 addition & 45 deletions src/hooks/__tests__/use-cached-state.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { render } from '@testing-library/react';
import { useCachedState, useClassNames, useReadOnlyCachedState } from '../use-cached-state';
import { useCachedState } from '../use-cached-state';
import Chance from 'chance';

const chance = new Chance();
Expand All @@ -24,48 +24,4 @@ describe('Cached State Hooks', () => {
expect(component.getByText(expectedValue)).toBeTruthy();
});
});

describe('hook(useReadOnlyCachedState)', () => {
type ExampleComponentProps = {
value: string;
};

function ExampleComponent({ value }: ExampleComponentProps) {
const internalValue = useReadOnlyCachedState(() => value, [value]);

return <div>{internalValue}</div>;
}

it('should cache the value', () => {
const expectedValue = chance.string();

const component = render(<ExampleComponent value={expectedValue} />);

expect(component.getByText(expectedValue)).toBeTruthy();
});
});

describe('hook(useClassNames)', () => {
type ExampleComponentProps = {
sticky?: boolean;
};

function ExampleComponent({ sticky }: ExampleComponentProps) {
const classes = useClassNames(['my-class', sticky && 'sticky']);

return <div data-testid="example" className={classes} />;
}

it('should support base classes', () => {
const component = render(<ExampleComponent />);

expect(component.getByTestId('example').className).toEqual('my-class');
});

it('should support conditional classes', () => {
const component = render(<ExampleComponent sticky />);

expect(component.getByTestId('example').className).toEqual('my-class sticky');
});
});
});
21 changes: 1 addition & 20 deletions src/hooks/use-cached-state.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import classNames, { ArgumentArray } from 'classnames';
import { DependencyList, useEffect, useMemo, useState } from 'react';
import { DependencyList, useEffect, useState } from 'react';

/**
* Gives you a state value that is automatically updated whenever its dependencies change.
Expand All @@ -17,21 +16,3 @@ export function useCachedState<T>(

return [value, setValue];
}

/**
* @deprecated this will be removed in v2.0.0, please swap to [useMemo](https://react.dev/reference/react/useMemo) before then.
* @see https://react.dev/learn/you-might-not-need-an-effect
*/
export function useReadOnlyCachedState<T>(supplier: () => T, deps: DependencyList): T {
const [value] = useCachedState(supplier, deps);

return value;
}

/**
* @deprecated At best `useClassNames` is unnecessary and at worst it hurts performance. As such this will be removed in v2.0.0
* @see https://react.dev/learn/you-might-not-need-an-effect
*/
export function useClassNames(deps: ArgumentArray): string {
return useMemo(() => classNames(deps), deps);
}
3 changes: 3 additions & 0 deletions src/react-helmet-async.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/* c8 ignore start */
export * from './tests/libs/react-helmet-async';
/* c8 ignore end */
3 changes: 3 additions & 0 deletions src/react-query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/* c8 ignore start */
export * from './tests/libs/react-query';
/* c8 ignore end */
3 changes: 3 additions & 0 deletions src/react-router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/* c8 ignore start */
export * from './tests/libs/react-router';
/* c8 ignore end */
19 changes: 19 additions & 0 deletions src/tests/libs/__tests__/react-helmet-async.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { render, waitFor } from '@testing-library/react';
import { Helmet } from 'react-helmet-async';
import { HelmetProvider } from '../react-helmet-async';

describe('wrappers(react-router-dom)', () => {
describe('wrapper(Router)', () => {
it('should be a MemoryRouter', async () => {
const MyComponent = await HelmetProvider(() => (
<Helmet>
<title>Test</title>
</Helmet>
));

render(<MyComponent />);

await waitFor(() => expect(document.title).toEqual('Test'));
});
});
});
22 changes: 22 additions & 0 deletions src/tests/libs/__tests__/react-query.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { render, screen } from '@testing-library/react';
import { QueryClientProvider } from '../react-query';
import { useQuery } from '@tanstack/react-query';

describe('wrappers(react-query)', () => {
describe('wrapper(QueryClientProvider)', () => {
it('should support queries', async () => {
const MyComponent = await QueryClientProvider(() => {
const { data } = useQuery({
queryKey: ['test'],
queryFn: () => 'Test',
});

return data;
});

render(<MyComponent />);

await expect(screen.findByText('Test')).resolves.toBeTruthy();
});
});
});
19 changes: 19 additions & 0 deletions src/tests/libs/__tests__/react-router.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Route, Routes } from 'react-router-dom';
import { render, screen } from '@testing-library/react';
import { MemoryRouter } from '../react-router';

describe('wrappers(react-router-dom)', () => {
describe('wrapper(MemoryRouter)', () => {
it('should be a MemoryRouter', async () => {
const MyComponent = await MemoryRouter(() => (
<Routes>
<Route index element={'Index'} />
</Routes>
));

render(<MyComponent />);

expect(screen.getByText('Index')).toBeTruthy();
});
});
});
4 changes: 4 additions & 0 deletions src/tests/libs/react-helmet-async.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { wrap } from '@rain-cafe/react-utils';
import { HelmetProvider as Provider } from 'react-helmet-async';

export const HelmetProvider = wrap(Provider);
12 changes: 12 additions & 0 deletions src/tests/libs/react-query.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { wrap } from '@rain-cafe/react-utils';
import { QueryClient, QueryClientProvider as Provider } from '@tanstack/react-query';

export const QueryClientProvider = wrap(Provider, () => ({
client: new QueryClient({
defaultOptions: {
queries: {
retry: false,
},
},
}),
}));
4 changes: 4 additions & 0 deletions src/tests/libs/react-router.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { wrap } from '@rain-cafe/react-utils';
import { MemoryRouter as Memory } from 'react-router-dom';

export const MemoryRouter = wrap(Memory);
6 changes: 5 additions & 1 deletion src/tests/wrap.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { ComponentProps, ElementType, useMemo } from 'react';

export type SupportedComponentFormats<C extends React.ElementType> = C | Promise<C | { Component: C } | { default: C }>;
type BaseComponentFormats<C extends React.ElementType> = C | { Component: C } | { default: C };

export type SupportedComponentFormats<C extends React.ElementType> =
| BaseComponentFormats<C>
| Promise<BaseComponentFormats<C>>;

async function getComponent<C extends React.ElementType>(value: SupportedComponentFormats<C>): Promise<C> {
const response = await value;
Expand Down
5 changes: 4 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,10 @@
"isolatedModules": true,
"jsx": "react-jsx",
"jsxFactory": "",
"jsxFragmentFactory": ""
"jsxFragmentFactory": "",
"paths": {
"@rain-cafe/react-utils": ["./src/index.ts"]
}
},
"exclude": ["node_modules"]
}

0 comments on commit ea6db18

Please sign in to comment.