Posts

Showing posts from March, 2017

How To Mock Out Child Components In Unit Tests of Angular 2 Code

I was struggling with this one for a bit but found a solution this past weekend. When writing unit tests of a component that contains child components, the solution is to do the following: 1.       Create small mock classes in your test file to represent the child components and include just the functionality you’ll be mocking. These classes should have the @Component() decorator applied to them and contain selectors that match the real components they are being substituted for. 2.       Specify these mock components in the declarations section of the object you’re passing to TestBed.configureTestingModule(). Example: ActivityMgmtComponent has a few child components. Here are two of them: < activity-edit   #viewEditActivity ></ activity-edit > < activity-history   #viewActivityHistory ></ activity-history > Notice the # values – these are there to support the @ViewChild decorator function. This allows the parent component to call functions