Skip to content
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
38 changes: 35 additions & 3 deletions src/Piqure.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';

import { key, piqure, piqureWrapper } from './Piqure';
import { key, keyFor, piqure, piqureWrapper } from './Piqure';

describe('Piqure', () => {
it.each([
Expand Down Expand Up @@ -44,6 +44,13 @@ describe('Piqure', () => {
expect(inject(KEY)).toBe('New value');
});

it('Should create unique symbols for each key call with the same description', () => {
const FIRST_KEY = key<string>('Key');
const SECOND_KEY = key<string>('Key');

expect(FIRST_KEY).not.toBe(SECOND_KEY);
});

describe('With memory', () => {
it('Should attach', () => {
const memory = new Map();
Expand Down Expand Up @@ -88,15 +95,15 @@ describe('Piqure', () => {
});

describe('Lazy Provider', () => {
it('should get lazy value', () => {
it('Should get lazy value', () => {
const { provideLazy, inject } = piqure();
const LAZY_KEY = key('Lazy key');
provideLazy(LAZY_KEY, () => 'Lazy value');

expect(inject(LAZY_KEY)).toBe('Lazy value');
});

it('should get value once', () => {
it('Should get value once', () => {
const { provideLazy, inject } = piqure();
let count = 0;
const LAZY_KEY = key('Lazy key');
Expand All @@ -112,4 +119,29 @@ describe('Piqure', () => {
expect(count).toBe(1);
});
});

describe('keyFor', () => {
it('Should return the same symbol for the same description', () => {
const FIRST_KEY = keyFor<string>('Key');
const SECOND_KEY = keyFor<string>('Key');

expect(FIRST_KEY).toBe(SECOND_KEY);
});

it('Should be different from key with the same description', () => {
const LOCAL_KEY = key<string>('Key');
const GLOBAL_KEY = keyFor<string>('Key');

expect(LOCAL_KEY).not.toBe(GLOBAL_KEY);
});

it('Should work with provide and inject', () => {
const { provide, inject } = piqure();
const GLOBAL_KEY = keyFor<string>('my-service');

provide(GLOBAL_KEY, 'injected value');

expect(inject(GLOBAL_KEY)).toBe('injected value');
});
});
});
2 changes: 2 additions & 0 deletions src/Piqure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,5 @@ export const piqure = (memory: Map<unknown, Value<unknown>> = new Map()): Piqure
};

export const key = <T>(description: string): InjectionKey<T> => Symbol(description) as InjectionKey<T>;

export const keyFor = <T>(description: string): InjectionKey<T> => Symbol.for(description) as InjectionKey<T>;