how to force `onDestroy` hook invokation from a ngrx signal store in unit test?

Discussão em 'Angular' iniciado por Sergio Mazzoleni, Novembro 10, 2024.

  1. I'm using a SignalStore from @ngrx/signals in an Angular project.

    My store has onInit and onDestroy hooks invoking methods from a dependency injected in the store.

    import { signalStore, withHooks } from '@ngrx/signals';

    class SomeDependency {
    start() {
    throw new Error('real implementation not relevent');
    }
    stop() {
    throw new Error('real implementation not relevent');
    }
    }

    const MyStore = signalStore(
    withHooks((_store, dependency = inject(SomeDependency)) => ({
    onInit() {
    dependency.start();
    },
    onDestroy() {
    dependency.stop();
    },
    })),
    );


    I'm able to test that dependency.start() is properly invoked when creating the store

    it('should start dependency when created', () => {
    const fakeDependency = { start: jest.fn(), stop: jest.fn() };
    TestBed.configureTestingModule({
    providers: [MyStore, { provide: SomeDependency, useValue: fakeDependency }],
    });

    TestBed.inject(MyStore);

    expect(fakeDependency.start).toHaveBeenCalledOnce(); // test pass ✅
    });


    I am looking for a way to test that dependency.stop() is invoked when the store is somehow destroyed, but how can I force the store destruction?

    it('should stop dependency when destroyed', () => {
    const fakeDependency = { start: jest.fn(), stop: jest.fn() };
    TestBed.configureTestingModule({
    providers: [MyStore, { provide: SomeDependency, useValue: fakeDependency }],
    });
    const store = TestBed.inject(MyStore);

    // MISSING: force store descruction here

    expect(fakeDependency.stop).toHaveBeenCalledOnce(); // test fail ❌
    });

    Continue reading...

Compartilhe esta Página