Monday, July 10, 2023

.Net Dependency Injection Options

I was asked today by a colleague about the differences between AddScoped, AddTransient, and AddSingleton. I generally know the differences, but struggled to explain them to her. Fortunately, a quick Google search lead me to a super easy answer.

First, here's the full Stack Overflow answer. There's a TL;DR right at the top that says:

  •  Transient objects are always different; a new instance is provided to every controller and every service
  • Scoped objects are the same within a request, but different across different requests
  • Singleton objects are the same for every object and every request 

That summary comes from this Microsoft tutorial on configuring Dependency Injection.

Monday, April 17, 2023

Unit Test and Code Coverage Reports with Angular

I recently endeavored to have code coverage available as a metric in Azure DevOps for my Angular application. It turned out to be a little bit (but not much) trickier than I thought it would be so here I am.

I started with this two part article on how to get started, but had to make a few tweaks. You should go read those posts if they're still up, then come back here and skip down to the heading "The Changes".

The Summary

The first thing we have to do is get our test results generated locally. The linked posts above use junit and that met my needs so that's what I'm doing as well.

  1. Install the junit karma reporter: npm install karma-junit-reporter --save-dev
  2. Configure Karma to require junit
    • In karma.conf.js, add require('karma-junit-reporter') to the plugins array (which should already require things like karma-jasmine)
  3. Configure Karma to use junit as a reporter
    • In karma.conf.js, add 'junit' to the reporters array (which should already include 'progress' and 'kjhtml')
  4. Configure the junit reporter within Karma
    • In karma.conf.js, add the following configuration as a sibling of the reporters array in the previous step:
      •         junitReporter: {
          outputDir: 'reports/junit',
          outputFile: 'unit-test-results.xml',
          useBrowserName: false
        }
        		
        		
    • This configuration uses junit to create a file named unit-test-results.xml in a folder named reports/junit as a sibling of the src folder
    • Change the values of outputDir and outputFile to use a different file/folder combination
  5. Make sure Karma is configured to use a headless browser
    • The browsers array accepts ChromeHeadless as a value (it also accepts FirefoxHeadless, but I've had issues with headless Firefox holding on to resources and crashing my system so I tend to avoid it)
  6. We can now run ng test --watch=false to run all of our unit tests once and generate test results

Now that we have test results in an XML file we want to add code coverage results as well. We're going to use karma-coverage to do that part.

  1. Install the karma coverage reporter: npm install karma-coverage --save-dev
  2. Configure Karma to require karma coverage
    • In karma.conf.js, add require('karma-coverage') to the plugins array (the same array from step 2 in the previous section)
  3. Configure Karma to use karma coverage as a reporter
    • In karma.conf.js, add 'coverage' to the reporters array
  4. Configure the karma coverage reporter the way you want it
    • When you use the Angular CLI, karma-coverage is actually configured by default, but you may want to change the values
    • You can see the default configuration by looking for the coverageReporter node that is a sibling of the reporters array
    • I changed mine to output the file in the same reporters folder as the unit test results (reports/), in a subfolder called coverage
      • dir: require('path').join(__dirname, './reports/coverage'),
    • I also removed the text-summary reporter configuration and added the cobertura reporter configuration, specifying the file name to be code-coverage.xml
      • coverageReporter: {
          dir: require('path').join(__dirname, './reports/coverage'),
          subdir: '.',
          reporters: [
            { type: 'html' },
            {
              type: 'cobertura',
              file: 'code-coverage.xml'
            }
          ]
        }
        
        
  5. We can now run ng test --watch=false --code-coverage to run all of our unit tests once and generate test results and code coverage results
  6. The last thing we need to do is exclude files from code coverage that we don't want to... well, include
    • In angular.json, locate the projects/<project name>/architect/test node and add a codeCoverageExclude property, which is an array of strings
      • In the array, specify each fully qualified path - starting with src - to exclude from code coverage

That's it! Just like that, we have unit tests and code coverage results, but now we want to display those results in Azure DevOps. It turns out that's pretty easy, too.

  1. In your package.json, create a script to run your tests without watching and with code coverage results generated, to make it easier to do this from your build
    • "test-code-coverage": "ng test --watch=false --code-coverage"
  2. Create a new build (or add a test step to your current build, but I prefer to run my unit tests when a pull request is created rather than while I'm trying to deploy something)
    • pool:
        name: Azure Pipelines
      steps:
        - task: Npm@1
          displayName: 'npm install'
          inputs:
            verbose: false
        
        - task: Npm@1
          displayName: 'Execute tests'
          input:
            command: custom
            verbose: false
            customCommand: 'run test-code-coverage'
            
        - task: PublishTestResults@1
          displayName: 'Publish Test Results - Generate Test Report'
          inputs:
            testResultsFiles: '**/reports/junit/unit-test-results.xml'
            
        - task: PublishCodeCoverageResults@1
          displayName: 'Unit Test Code Coverage Report'
          inputs:
            codeCoverageTool: Cobertura
            summaryFileLocation: '**/reports/coverage/code-coverage.xml'
      
  3. As long as you publish your test results to the pipeline (as in the sample YAML above), Azure DevOps will automatically pick up the results and display them in a nice little UI for you

Thursday, March 23, 2023

From Waterfall to Scrum: A Software Development Journey

If you've spent any time working with software developers in the past 20 years you've probably heard the terms "waterfall", "agile", and "scrum" with varying levels of derision. I've been writing software for most of those 20 years and I have some... let's say strong... feelings about those terms. Since this is my blog and I get to write whatever I want, I figured I'd take a crack at explaining these things and why they are derided, fairly and unfairly.

Waterfall

Waterfall is kind of a catch-all term most commonly used as a synonym for "the worst way to develop software" these days. In my humble opinion, that is absolutely spot-on. Waterfall sucks. An oft-cited problem with the waterfall development model is that it takes too long to deliver anything. Waterfall got its name from the way the phases of the project look in project planning software: the first phase has to complete before the next phase can begin. 


I'll give you an example: I once worked as a consultant for a major health insurance company. They had a major initiative, the details of which I can't even remember anymore, but it was a Big DealTM. To accomplish this major initiative, the Powers That Be spent a significant amount of time setting forth everything they wanted the initiative to encompass. I have no idea how long they spent on this venture, but when they were finished they turned over an 18 page document of "business requirements". One of my fellow consultants then spent several weeks (I think six, but I could be wrong) converting that business requirements document into a technical requirements document. Then we started working on the actual code. We spent six-ish months implementing every single scenario we could think of that might come up during testing in order to fulfill those technical requirements and we finally delivered what we had to QA. They destroyed it. They had built test cases around the original business requirements, we had written our code based on the technical requirements, and apparently some things had been lost in translation. The translator had since left the consulting firm. Everything was a mess. We spent another two weeks fixing the code, then two more weeks having it all tested again and it was finally ready. Roughly 8 months after it was requested. It was not what the Powers That Be had envisioned and the changes were scrapped.

If Waterfall is so bad, why did we use it? Well, because it worked. Software used to be delivered on much longer timelines. If you're old enough to think about computers and software in the '90s, we weren't cranking out new features on any kind of regular basis because there was no reason to. Even Windows didn't really have patches, and if they did they had to be shipped out on floppy disks. The Internet changed everything. With the Internet - particularly high speed Internet service - we could deliver updates to software quickly and easily to all of our customers, and our customers knew that and (rightfully) demanded bug fixes. Waterfall was still the dominant software development methodology, but that wasn't going to work for the future.

Agile

Enter Agile. I've made a few jumps from Waterfall to Agile, but ultimately those jumps are small stepping stones on the larger path from Waterfall to Agile (the generically named iterative development is one such stepping stone, which was basically waterfall, but with shorter cycles). What is Agile? This is where things start to get confusing for people, I think. Agile is "a mindset". Super helpful, right? What the hell does it mean to be "a mindset"? In this case it simply means we're going to think about delivering software differently than we used to. The Agile Mindset was delivered unto us in the form of The Agile Manifesto.

A group of software folks got together and asked themselves how they could write software better. They came up with some bullet points they could refer back to and they published those bullet points as The Agile Manifesto. The Agile Manifesto makes some suggestions about what we can do to deliver better software that our customers actually want, but doesn't tell us anything about how to do it. It's just a list of suggestions on how we might do things, based on collectively decades (at that time) of software development experience. That's all Agile is. That's it. Agile doesn't prescribe a set of activities or actions or how we define requirements or anything. It's just a general set of suggestions (a mindset) that we can follow to write and deliver better software. Full stop.

Scrum

We've finally arrived at the much-maligned Scrum. In my experience people either love it or hate it, and they usually fall on the hate side. You can find a ton of hate online for Scrum (check out r/programmerhumor on Reddit if you want a taste) or just talk to pretty much any developer who has ever been subjected to daily standups that go on for an hour and planning meetings where nothing much gets planned. They'll all say some variation of the same thing: Scrum just added meetings to my schedule and didn't actually help me deliver software any better. Unfortunately for those people - and the reputation of Scrum - that's just abusing the name of Scrum. When done properly, Scrum works. Let me start by briefly explaining what Scrum is and what it is not. Then I'll go into areas that I see go wrong the most often.

Scrum is honestly pretty simple. You can get the gist of it by reading the Scrum Guide (it takes 20 - 30 minutes), but I'll go over the basics here since you're already reading my blog. Scrum just puts a framework around the Agile methodology, dictating specific events and what must happen during those events. Scrum defines three roles that participate on a Scrum Team and what each of those roles is supposed to do.

Roles

Scrum Master

Scrum Master is probably the most hated on position in software engineering. I've heard developers say Scrum Masters are useless, they have to justify their job by making the Developers' lives hard, and they don't even bring anything valuable to the team. Scrum Masters are important, but if they're doing their job properly it looks like they're not doing much. The whole purpose of a Scrum Master is to - as I call it - shepherd the process (I'm sure I picked that up somewhere so don't go thinking too highly of my creativity). The Scrum Master introduces and supports Scrum as a concept and a framework to the Scrum Team and the organization as a whole. In the event Developers are prevented from moving forward for some reason the Scrum Master seeks to fix whatever is blocking them. It's a pretty straightforward job that I do while also being a contributing software engineer on the Scrum Team.

Product Owner

The Product Owner owns the product. S/he is responsible for working with users to figure out what to have the product do. The primary job of the Product Owner is to define what they want the product to do so the Development Team can build it. They do that by putting items on the Product Backlog (called - shockingly - Product Backlog Items) and then clarifying those requirements for the Development Team.

Developer

"Developer" comprises everyone on the Scrum Team who isn't the Product Owner or Scrum Master. Whether their skills are front-end, back-end, full-stack, testing, or anything else makes no difference. Everyone who participates on the work product to move it toward the Product Goal is a Developer. That's it.

Events

The events of Scrum are: The Sprint, Sprint Planning, Daily Scrum, Sprint Review, and Sprint Retrospective.

The Sprint

The Sprint is a bit of a unique "event" in that it is a container for all of the other events. The Sprint has a pre-defined time period of up to one month. The most common length of a Sprint in my experience is two weeks. During those two weeks, the Scrum Team works toward delivering an Increment - a set of deliverables that move the Scrum Team toward delivery of the Product Goal - while engaging in the rest of the Scrum Events.

Sprint Planning

At the beginning of the Sprint, the Scrum Team meets to review the Product Backlog - the list of all work that defines what the Product will be when it is complete - and determine which parts of the Product Backlog the Scrum Team believes they can complete during the Sprint. Product Backlog Items (PBIs) are measured by the team for their complexity: how tricky is the PBI going to be to implement, how much risk is involved in implementing it, and how much is unknown about what needs to be done. It is important (and difficult) to remember that complexity may not correlate to actual time spent on a PBI once the work is taken on. Complexity is commonly measured using story points in the Fibonacci sequence or "t-shirt sizes".

After the complexity is set for a PBI, I find it best to have the Developers break each PBI down into tasks and estimate the hours of each task. This is the best guess the Developers can make for each item based on their experience. They might end up working many more or many fewer hours on each task; these are just estimates. Once the Scrum Team agrees they have enough work to fill the duration of the Sprint, they stop bringing work in. However, the Sprint Planning meeting may continue so the Scrum Team can ask questions about future work and even perhaps assess complexity of future PBIs (without diving into the tasks of those stories). Doing this can help the Scrum Team provide an estimate for when a given PBI might get worked on.

Daily Scrum

The purpose of Daily Scrum is for the Developers to tell each other how things are going. It is an opportunity to explain to each other where they're stuck, what they learned, helpful tips about something they've been working on, or anything else relevant to the Sprint. Since Scrum Masters aren't managers and managers shouldn't be in the Daily Scrum there's no reason to provide information based on what management expects to hear. If you're doing that, you're doing Scrum wrong.

Sprint Review

In my opinion, Sprint Review and Retrospective are the most important events in Scrum (not that any of them are optional). Sprint Review is the time when the Scrum Team goes over what they accomplished during the Sprint. It is common for key stakeholders to join this meeting and provide feedback on what was delivered in the Increment as well as guidance for what they'd like to see in upcoming Increments. However, it is vital to not turn the Sprint Review into a demo. The feedback is the most important part so hearing what the Product Owner and stakeholders have to say is key to the success of the meeting. I like to tell people the Sprint Review is the opportunity to review and improve the Product so use this time to work to that end.

Sprint Retrospective

Finally we come to the Sprint Retrospective. This is an opportunity for the Scrum Team to meet alone (no management; no stakeholders; just Developers, the Scrum Master, and the Product Owner) to discuss how the Sprint went. There are lots of ways to design a good retrospective, but I like to use a site called Retromat to build a retrospective plan. As the Sprint Review is where the Scrum Team reviews and improves the Product, the Retrospective is where the Scrum Team reviews and adopts changes to the people and processes. For that reason, Retrospective has to be confidential and protected. Nothing should ever come out of Retrospective except Action Items (which are one to two concrete actions the Scrum Team agrees to take to improve). The team is free to discuss anything related to the Sprint as it relates to the team. Did someone constantly show up late to Daily Scrum? Say something. Did you feel like you did all the work in the Sprint? Say something.

The ultimate goal of the Sprint Retrospective is to be a better team, but that can't happen if people hold back their true feelings on how each sprint goes. Be open. Be honest. Be fair.

Misunderstandings

Everyone Does Scrum Differently

I think the easiest place to start is with the idea that Scrum is different at each company. That's not usually true. Scrum is a framework and while we are free to adapt within that framework we cannot operate outside the framework and still be doing Scrum. If you are doing Scrum then you are adhering to the Scrum framework. If you're not adhering to the Scrum framework then you're not doing Scrum. And that's OK! Sometimes Scrum isn't right for your organization so you can't adhere to the Scrum framework. There are lots of other methodologies out there that work very well. If you're aggravated by Scrum then look closely at what you were doing and compare that to the Scrum framework. My bet is you weren't actually doing Scrum.

Scrum Master as Team Lead/Manager

In my experience, this is commonly the result of the Scrum Masters themselves not understanding their role as a facilitator and instead falling into a team manager. I've seen Scrum Masters assign tasks to Developers. I've seen Scrum Masters ask Developers during Daily Scrum for a detailed update of the work they completed the previous day. You've probably seen worse. The Scrum Master is absolutely not above anyone and absolutely should not operate like they are.

Daily Scrum as a Report to Management

I've already touched on this, but it's worth repeating: Daily Scrum is the time for Developers to communicate with each other, not with management. Management shouldn't even be in the Daily Scrum and the Scrum Master isn't in charge of anything. Daily Scrum is just for Developers to communicate how well they're moving toward the Sprint Goal.

Daily Scrum as Only a Status Update

I'm beating a dead horse here, but it's a common gripe. Communicate. Communicate. Communicate! That's what Daily Scrum is for. If you find your Daily Scrum meetings entail a bunch of people droning on about what they did yesterday, what they plan to do today and how they have no impediments, you're probably not getting the most out of your Daily Scrum. Tell your teammates where you got stuck or what you're stuck on now, even if it doesn't seem to you like it's an impediment and even if you don't want anyone's help resolving the problem right now. It's an opportunity for someone else to say "Oh, I'm dealing with that exact same thing. What have you tried?" COMMUNICATE!

Work Can Change on the Fly

Once Sprint Planning has been completed, the work in the Sprint is fixed unless the Scrum Team agrees to change it. That explicitly does not mean the Product Owner can demand the Developers work on something new. There can be a negotiation process if priorities have changed or something urgent has come up since Sprint Planning, but it's always up to the whole team whether they change what they're working on. If you find you're constantly being asked to change work once the Sprint starts, try shortening your sprints.

Some Ceremonies are Optional

I can't stress this enough: all five Scrum Events are required. If you're not doing one of them, you're not doing Scrum. You don't cancel the Sprint Review because you don't think you completed enough. You don't cancel the Sprint Retrospective because last time no one participated. Every single event serves a purpose and every single event is absolutely required.

Conclusion

So that's it. That's my take on software development in the middle of my career. Scrum isn't perfect, but when you do it properly, it's damn good. And anything is better than waterfall.

Saturday, November 19, 2022

Testing with JsonPatchDocument in Asp.Net

I've written in the past about how to use the PATCH verb for updating individual properties on larger objects in a RESTful way. When it comes time to test those controller methods, it helps to have a way to reliably setup your test data. That's what this post is about.

I created a static class that I can use from my tests to create a JsonPatchDocument to pass to your tests. Here's what that class looks like:

   1:  using Microsoft.AspNetCore.JsonPatch;
   2:  using System;
   3:  using System.Linq.Expressions;
   4:  
   5:  namespace Blog.UnitTests.Utilities.Setup
   6:  {
   7:      public static class JsonPatchDocumentSetup
   8:      {
   9:          public static JsonPatchDocument<T> BuildJsonPatchDocument<T, TProp>(Expression<Func<T, TProp>> expr, TProp newObject, string type) where T : class
  10:          {
  11:              var jsonPatchDocument = new JsonPatchDocument<T>();
  12:  
  13:              switch (type)
  14:              {
  15:                  case "add":
  16:                      jsonPatchDocument.Add(expr, newObject);
  17:                      break;
  18:                  case "copy":
  19:                      jsonPatchDocument.Copy(expr, expr);
  20:                      break;
  21:                  case "move":
  22:                      jsonPatchDocument.Move(expr, expr);
  23:                      break;
  24:                  case "remove":
  25:                      jsonPatchDocument.Remove(expr);
  26:                      break;
  27:                  case "replace":
  28:                      jsonPatchDocument.Replace(expr, newObject);
  29:                      break;
  30:              }
  31:  
  32:              return jsonPatchDocument;
  33:          }
  34:  
  35:          public static JsonPatchDocument<T> AppendToJsonPatchDocument<T, TProp>(this JsonPatchDocument<T> jsonPatchDocument, Expression<Func<T, TProp>> expr,
                                                TProp newObject, string type) where T : class
  36:          {
  37:              switch (type)
  38:              {
  39:                  case "add":
  40:                      jsonPatchDocument.Add(expr, newObject);
  41:                      break;
  42:                  case "copy":
  43:                      jsonPatchDocument.Copy(expr, expr);
  44:                      break;
  45:                  case "move":
  46:                      jsonPatchDocument.Move(expr, expr);
  47:                      break;
  48:                  case "remove":
  49:                      jsonPatchDocument.Remove(expr);
  50:                      break;
  51:                  case "replace":
  52:                      jsonPatchDocument.Replace(expr, newObject);
  53:                      break;
  54:              }
  55:  
  56:              return jsonPatchDocument;
  57:          }
  58:      }
  59:  }

And here are some examples of how you'd use it:

   1:  using Blog.BusinessLogic.Implementations;
   2:  using System.Collections.Generic;
   3:  using System.Threading.Tasks;
   4:  using Xunit;
   5:  
   6:  namespace Blog.BusinessLogic.UnitTests.Implementations
   7:  {
   8:      public class BlogClassUnitTests
   9:      {
  10:          ...test class setup...
  11:          [Theory]
  12:          [InlineData(true, true)]
  13:          [InlineData(true, false)]
  14:          [InlineData(true, null)]
  15:          [InlineData(null, true)]
  16:          [InlineData(null, false)]
  17:          [InlineData(null, null)]
  18:          [InlineData(false, true)]
  19:          [InlineData(false, false)]
  20:          [InlineData(false, null)]
  21:          public async Task DoingTheThingShouldDoWhatIsExpectedUsingInlineData(bool? firstUpdatedValue, bool? secondUpdatedValue)
  22:          {
  23:              // arrange
  24:              var jsonPatchDocument = JsonPatchDocumentSetup.BuildJsonPatchDocument<UpdateableViewModel, bool?>(p => p.FirstUpdateableProperty, firstUpdatedValue, "replace");
  25:              jsonPatchDocument.AppendToJsonPatchDocument(p => p.SecondUpdateableProperty, secondUpdatedValue, "replace");
  26:              ...additional setup...
  27:  
  28:              // act
  29:              ...take action...
  30:  
  31:              // assert
  32:              ...make assertions...
  33:          }
  34:  
  35:          public static IEnumerable<object[]> BlogTestCases
  36:          {
  37:              get
  38:              {
  39:                  return new[]
  40:                  {
  41:                      new object[]
  42:                      {
  43:                          new UpdateableViewModel
  44:                          {
  45:                              FirstUpdateableProperty = true
  46:                              NestedUpdateableProperty = new NestedUpdateableViewModel()
  47:                              SecondUpdateableProperty = false
  48:                          },
  49:                          (Expression<Func<UpdateableViewModel, NestedUpdateableViewModel>>)(p => p.NestedUpdateableProperty),
  50:                          new NestedUpdateableViewModel{Id = 987},
  51:                          new UpdateableViewModel
  52:                          {
  53:                              FirstUpdateableProperty = true
  54:                              NestedUpdateableProperty = new NestedUpdateableViewModel{Id = 987}
  55:                              SecondUpdateableProperty = false
  56:                          }
  57:                      }
  58:                  }
  59:              }
  60:          }
  61:  
  62:          [Theory, MemberData(nameof(BlogTestCases))]
  63:          public async Task DoingTheThingShouldDoWhatIsExpectedUsingMemberData<TProp1, TProp2>(UpdateableViewModel currentViewModel, Expression<Func<UpdateableViewModel, TProp1>> expression, TProp1 newObject, UpdateableViewModel expected)
  64:          {
  65:              // arrange
  66:              var jsonPatchDocument = JsonPatchDocumentSetup.BuildJsonPatchDocument&lt(expression, newObject, "replace");
  67:              ...additional setup...
  68:  
  69:              // act
  70:              ...take action...
  71:  
  72:              // assert
  73:              ...make assertions...
  74:          }
  75:      }
  76:  }

Hopefully next time I need this I remember I wrote this post, or maybe somebody else comes across this and it helps them with unit testing their own code. Maybe some day I'll turn this into a NuGet package. Ah, to dream.

Friday, July 22, 2022

Dynamic QueryParams with RouterLink

This is something that should have been obvious, but still required me to find an answer on SO. As I do, I'm putting it here to make it easier to find in the future. Basically I wanted to use an anchor tag with the routerLink directive, but send out dynamic parameters and I couldn't figure out how to do it. It turns out you can just bind the queryParams part of routerLink to a property on your component and pass it that way.

component.ts

<snip>...<snip>
public dynamicQueryParams: Params;
<snip>...<snip>
this.dynamicQueryParams = {first: 'value', second: 'empty'};
<snip>...<snip>

component.html

<snip>...<snip>
<a [routerLink]="['/support/case-history']" [queryParams]="dynamicQueryParams" target="_blank">Click Me!</a>
<snip>...<snip>
That's pretty much it. Obviously, you'll need to build your dynamicQueryParams variable the way you want it, but this is how you can pass dynamic parameters via a routerLink directive.

Monday, July 18, 2022

No value accessor for form control with name

 I'm going to be brief here and hopefully circle back to this with more details later. As of today (July 18, 2022) there is an open issue in the Angular Github repository stating the team should try to improve this error message. I wish they would because today I wasted two hours on something really stupid. Ultimately, it was my fault for doing the wrong thing, but the whole point of error messages should be to help you find and fix the error.

Anyway, what happened to me today is I was using a 3rd party component (Kolkov Angular Editor) and it was throwing an error that originally said "No value accessor for form control with unspecified name attribute". After some trial and error and moving a bunch of stuff around I thought I had identified that the problem was caused by the 3rd party control itself and there was some bug in it. I applied a workaround that fixed it in one place, but not the other. Eventually, I was able to piece together that I was importing the 3rd party module in my wrong module.

My app is broken up (as it should be) into separate modules by purpose. Then I have one SharedModule where I declare, import, and export anything that's used across multiple modules in my app. When I originally built the piece that uses the Kolkov Angular Editor I had it all in one module, but as my app grew I moved some of my components into my SharedModule, but left the importation of the Kolkov module in its original place. That was the root of my problem. Once I moved the import (and export) into my SharedModule everything worked perfectly. And it only took me two hours to figure out.

Monday, May 23, 2022

No provider for ControlContainer!

As you can probably deduce from the title, this post is all about an annoying error in Angular that reads "No provider for ControlContainer!". If you're just getting this error in general, the first thing you should do is make sure you've imported the FormsModule and ReactiveFormsModule (yes, both of them). That will probably clear it up for you. If you've done that and you're still getting this error, specifically while running your unit tests, I have a solution for you. I'm nearly 100% certain I didn't come up with this on my own, but since I'm not sure where I originally found it I can't link you over to it. Sorry for that.

First off, let me show you the code that triggered this issue when I started testing. Like a good programmer following DRY (Don't Repeat Yourself) I will often componentize even small things that are reused and require some bit of setup or configuration. For instance, when creating forms that require masked input fields (like phone number or credit card) I'll create a component that allows me to quickly and easily drop that into my form and just specify which mask to use. The way I do that requires me to inject ControlContainer directly into the component. Here's some example code:

import { Component, Input, OnInit } from '@angular/core';
import { ControlContainer, FormControl, FormGroup } from '@angular/forms';

@Component({
  selector: 'app-masked-input'
  templateUrl: './masked-input.html'
})
export class MaskedInputComponent implements OnInit {
  @Input() controlName: string;
  @Input() label: string;
  @Input() mask: any;

  constructor(public controlContainer: ControlContainer) { }

  public ngOnInit(): void {
    // Set our form property to the parent control
    // (i.e. FormGroup) that was passed to us, so that our
    // view can data bind to it
    this.form = this.controlContainer.control as FormGroup;
    this.control = this.form.get(this.controlName) as FormControl;
  }
}

That's the relevant part to this error. If we try to run unit tests around that code we'll get the error "No provider for ControlContainer!" even if we import FormsModule and ReactiveFormsModule in our test file. To fix that error, we have to manually create a FormGroupDirective in our test file and change the provider for ControlContainer to use that FormGroupDirective. Here are the relevant bits of code:

import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ControlContainer, FormControl, FormGroup, FormGroupDirective, FormsModule, ReactiveFormsModule } from '@angular/forms';
...snip...
describe('MaskedInputComponent'), () => {
  let component: MaskedInputComponent;
  let fixture: ComponentFixture<MaskedInputComponent>;
  const formGroup: FormGroup = new FormGroup({
    dynamicControlName: new FormControl('')
  });
  const formGroupDirective: FormGroupDirective = new FormGroupDirective([], []);
  formGroupDirective.form = formGroup;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ MaskedInputComponent ],
      imports: [ FormsModule, ReactiveFormsModule ],
      providers: [ { provide: ControlContainer, useValue: formGroupDirective } ],
    })
    compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MaskedInputComponent);
      component = fixture.componentInstance;
      component.controlName = 'dynamicControlName';
      fixture.detectChanges();
    })
    compileComponents();
  });
});

That's it! This will alleviate the "No provider for ControlContainer!" error in your test run. It's simple enough once you know what to do, but it was a pain figuring it out. Hope this helps.