Original cover photo by Liam Tucker on Unsplash.
Original publication date: 2020-09-19.
Route guards can prevent activating or deactivating speci...
For further actions, you may consider blocking this person and/or reporting abuse
Very nice! I appreciate this article. I could not find any other valuable information on how to test guards nicely.
Too long write up but it does show the way towards navigation guard testing.
One question: why wrap navigation step inside NgZone.run when the navigation API's i-e router.navigate() and router.navigateByUrl() already return a promise ? Why not just use await like
or
When we use the TestBed we need to emulate parts of the Angular framework such as trigger change detection. The TestBed doesn't bootstrap an Angular application. No longer are all events caught by the NgZone triggering change detection. This is also the case here. If we don't wrap
Router#navigate*
inNgZone#run
in tests, a warning is triggered.Lars, in your tests you just check whether the navigation went through or was denied, right ?
So, was triggering change detection still necessary ?
If we want to avoid warnings, yes. The warning will say that a scheduled event happened outside of the NgZone.
We also want to make sure that changes are stable as they would be in an app.
How would you test guards when they get created from a factory fn, and the service is injected using the new
inject()
function. Something like:canActivate: [ getGuard('accessFlag') ]
. The isolated approach in that case seems to be challenging -inject()
requires a context and you no longer use the constructor then.You can use an integrated test with
RouterTestingModule
as described in this article or you can use an isolated unit test that usesTestBed
to set up test doubles.Thanks, was also testing my guard factory whether it returns a callable function, but not sure it is needed - feels like not trusting TypeScript ;-) At any rate. thank you for this reply, I think it would be a good extension of your article anyway.
Not 100% sure that the above example works. See netbasal.com/testing-di-functions-...
Mind blowing, learned so much. Only one of it's kind that deals with routes/guards testing so thoroughly. thanks so much!
Great, great article! Awesome... Thanks for sharing.