Add context test

This commit is contained in:
Alejandro Celaya 2025-11-15 10:57:39 +01:00
parent 4b655761c6
commit b6f1db57ee
3 changed files with 41 additions and 2 deletions

View File

@ -8,7 +8,7 @@ export const ContainerProvider = ContainerContext.Provider;
export const useDependencies = <T extends unknown[]>(...names: string[]): T => {
const container = useContext(ContainerContext);
if (!container) {
throw new Error('You cannot use "useDependency" outside of a ContainerProvider');
throw new Error('You cannot use "useDependencies" outside of a ContainerProvider');
}
return names.map((name) => {

View File

@ -0,0 +1,39 @@
import { render } from '@testing-library/react';
import { fromPartial } from '@total-typescript/shoehorn';
import { ContainerProvider, useDependencies } from '../../src/container/context';
describe('context', () => {
describe('useDependencies', () => {
let lastDependencies: unknown[];
function TestComponent({ name}: { name: string }) {
// eslint-disable-next-line react-compiler/react-compiler
lastDependencies = useDependencies(name);
return null;
}
it('throws when used outside of ContainerProvider', () => {
expect(() => render(<TestComponent name="foo" />)).toThrowError(
'You cannot use "useDependencies" outside of a ContainerProvider',
);
});
it('throws when requested dependency is not found in container', () => {
expect(() => render(
<ContainerProvider value={fromPartial({})}>
<TestComponent name="foo" />
</ContainerProvider>,
)).toThrowError('Dependency with name "foo" not found in container');
});
it('gets dependency from container', () => {
render(
<ContainerProvider value={fromPartial({ foo: 'the dependency' })}>
<TestComponent name="foo" />
</ContainerProvider>,
);
expect(lastDependencies).toEqual(['the dependency']);
});
});
});

View File

@ -65,7 +65,7 @@ export default defineConfig({
thresholds: {
statements: 95,
branches: 89, // FIXME Increase to 95 again. It dropped after updating to vitest 4
functions: 95,
functions: 93,
lines: 95,
},
},