Posts

Showing posts from November, 2024

How to Cast an Injected Service as a Mock in Angular Unit Tests

I've been meaning to write this for a while. Normally in my Angular unit tests, I set up my service mocks and then let dependency injection treat them as if they're the real thing. But sometimes you'll need to cast a service mock as a spy so you can do things like reset the calls it's made. And it's one of those things I always have to think back and remember "How did I do that last time?". Here's an example of how: const mockScoreAdminService = TestBed.inject(ScoreAdminService) as jasmine.SpyObj<ScoreAdminService>; mockScoreAdminService.processScores.calls.reset(); This code casts the service mock, which is treated as the real service type, to a Jasmine spy object. It then resets the calls made to the processScores  method to zero. I hope this helps someone!

Setting Default Values in an Angular Reactive Form

Something I ran into a few months back was that Angular won't reset a FormControl back to its initial value if you call reset()  on the FormGroup unless that FormControl was created with nonNullable: true . Here's an example:   private createForms ( formBuilder : FormBuilder ) : void {     //For the initial values to be considered the *default* values, we need to specify nonNullable: true.     //There used to be a dedicated property for this, but they deprecated it.     this . searchForm = formBuilder . group < ISearchForm >({       adminYear : new FormControl < number >( null , { validators : Validators . required }),       admin : new FormControl < string >( 'All' , { nonNullable : true , validators : Validators . required }), //Validator is kind of pointless here, as there WILL always be a value       examName : new FormControl < string | null >( null ), ...