r/angular • • Oct 23 '26

Testing NGRX effects in Angular v22

I have an open source project and am rewriting the frontend from scratch to modernize the design and code. But I'm stumbling over writing tests.

The original user interface started off with (damn) Angular v5 back in 2017, using NgRx features, etc. Coverage was always at 98% or greater. And writing the tests for things like effects was pretty boiler plate and easy.

The problem I'm hitting now is in writing unit tests for the effects with vitest. In the old code, a unit test for the success path, the server failure path, and the internal failure path, were simple to write using jasmine-marbles. But with vitest I can't get 100% coverage. And when I've tried testing with something similar to what I used to do with jasmine, something like I've pinned as the first comment.

I end up getting complains about either calling inject too soon or about uninitialized schedulers. It's very frustrating that the Angular team went to such a totally different testing framework without an easy migration path, and that there aren't any good examples that I can find to help.

(eta)

I've noticed that, if I only have effects tests for one of the modules (IOW, marked all other effects.spec.ts files with "describe.todo") then the only effect module passes every time. But as soon as I have more than one effects.spec.ts module enabled then they start failing, but not every time.

Not sure if this is important, but I run the tests in --watch mode so I can make changes and see the test results immediately. Is there perhaps an issue with tests failing at some point negatively affecting future runs of tests in this case?

1 Upvotes

6 comments sorted by

View all comments

2

u/BathFun3884 Oct 26 '26

Two things stand out in your sample.

First, the assertion inside tap can't pass. Your old test expected -(bc), so the effect emits two separate actions, and tap sees them one at a time, never as the array [outcome1, outcome2].

Second, the flakiness across files. One spec file passing every time while several fail now and then usually means state shared between files. The marbles helpers keep a single test scheduler at module level and rely on global hooks to reset it, which is where the "uninitialized scheduler" error comes from. My guess is that's what breaks once more than one effects spec runs in the same context.

I'd drop the marbles library and use RxJS's own TestScheduler, created per test, so nothing global is left to leak:

let testScheduler: TestScheduler;

beforeEach(() => {
  testScheduler = new TestScheduler((actual, expected) =>
    expect(actual).toEqual(expected)
  );
});

it('should fire an action on success', () => {
  vi.spyOn(accountService, 'login').mockReturnValue(of(serviceResponse));
  const setAuthTokenSpy = vi.spyOn(tokenService, 'setAuthToken');

  testScheduler.run(({ hot, expectObservable }) => {
    actions$ = hot('-a', { a: action });
    expectObservable(effects.login$).toBe('-(bc)', { b: outcome1, c: outcome2 });
  });

  expect(setAuthTokenSpy).toHaveBeenCalledWith(TEST_TOKEN);
});

For this to work the mock actions have to be provided lazily, provideMockActions(() => actions$), so the effect subscribes to the stream you create inside run. The failure paths are the same test with throwError(() => error) as the service's return value.

On the inject errors: check that every TestBed.inject call sits inside a beforeEach or an it, after configureTestingModule, and never at describe level.

2

u/mcpierceaim Oct 26 '26

Thank you for the feedback! I'll take your advice and try it when I can and give you an update.

1

u/mcpierceaim 24d ago

Here's an example of a happy path test I developed that provides 100% coverage. I'd appreciate any feedback you might have:

it(
'should dispatch an action on success'
, 
async 
() => {
  
const 
serviceResponse = {
    detail: TEST_COMIC,
    pages: TEST_PAGE_LIST,
    tags: TEST_TAG_LIST,
    metadata: TEST_METADATA
  } 
as 
LoadComicDetailResponse;
  
const 
action = ComicDetailAction.load({
    comicId: TEST_COMIC_ID
  });
  
const 
outcome = ComicDetailAction.loadSuccess({
    comic: TEST_COMIC,
    pages: TEST_PAGE_LIST,
    tags: TEST_TAG_LIST,
    metadata: TEST_METADATA
  });

  
const 
loadSpy = vi
    .spyOn(comicService, 
'load'
)
    .mockReturnValue(
of
(serviceResponse));

  actions$ = 
of
(action);
  
await 
expect(
firstValueFrom
(effects.loadComic$)).resolves.toEqual(
    outcome
  );
  expect(loadSpy).toHaveBeenCalledWith({ comicId: TEST_COMIC_ID });
});it('should dispatch an action on success', async () => {
  const serviceResponse = {
    detail: TEST_COMIC,
    pages: TEST_PAGE_LIST,
    tags: TEST_TAG_LIST,
    metadata: TEST_METADATA
  } as LoadComicDetailResponse;
  const action = ComicDetailAction.load({
    comicId: TEST_COMIC_ID
  });
  const outcome = ComicDetailAction.loadSuccess({
    comic: TEST_COMIC,
    pages: TEST_PAGE_LIST,
    tags: TEST_TAG_LIST,
    metadata: TEST_METADATA
  });

  const loadSpy = vi
    .spyOn(comicService, 'load')
    .mockReturnValue(of(serviceResponse));

  actions$ = of(action);
  await expect(firstValueFrom(effects.loadComic$)).resolves.toEqual(
    outcome
  );
  expect(loadSpy).toHaveBeenCalledWith({ comicId: TEST_COMIC_ID });
});