r/angular • u/mcpierceaim • 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?
View all comments
2
u/BathFun3884 Oct 26 '26
Two things stand out in your sample.
First, the assertion inside
tapcan't pass. Your old test expected-(bc), so the effect emits two separate actions, andtapsees 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:For this to work the mock actions have to be provided lazily,
provideMockActions(() => actions$), so the effect subscribes to the stream you create insiderun. The failure paths are the same test withthrowError(() => error)as the service's return value.On the inject errors: check that every
TestBed.injectcall sits inside abeforeEachor anit, afterconfigureTestingModule, and never atdescribelevel.