There is no shallow testing in our loved Angular. So, to test only your component without rendering children, you would need to use stub components in your TestBed. If you are bored to create stub components manually, this article is for you. We will use Angular/Schematics for this. [updated] Please install schematics-cli beforehand and make it global:

$ npm install -g @angular-devkit/schematics-cli
$ vim ~/.bash_profile
$ export PATH="/usr/local/lib/node_modules/@angular-devkit:$PATH"

Create our angular test application.

$ npm install -g @angular-devkit/schematics-cli
$ ng new myapp
$ cd myapp/node_modules
$ mkdir -p @custom/myangular
$ cp -R @schematics/angular/* @custom/myangular/ 
$ cd @custom/myangular/component/files/__name@dasherize@if-flat__/

After this, let’s add stub file to our newly created collection:

$ cp __name@dasherize__.component.ts stub.__name@dasherize__.component.ts

After this, change newly created file as this:

import { Component } from '@angular/core';
  
@Component({
  selector: '<%= selector %>',
  template: `
    <p>
      <%= dasherize(name) %> works!
    </p>
  `})
export class Stub<%= classify(name) %>Component {}

That is it, now you can create your stubbed component with the following command:

ng g @custom/myangular:component subbed
CREATE src/app/subbed/subbed.component.css (0 bytes)
CREATE src/app/subbed/subbed.component.html (25 bytes)
CREATE src/app/subbed/subbed.component.spec.ts (628 bytes)
CREATE src/app/subbed/subbed.component.ts (269 bytes)
CREATE src/app/subbed/stub.subbed.component.ts (178 bytes)
UPDATE src/app/app.module.ts (396 bytes)

We can package @custom/myangular as npm module and install it with npm. Also it is better not copy but extend default @schematics/angular. I will write about this later. To be continued… Thank you for reading

I was guided with this post of Philippe Martin during writing of this article.

Leave a Reply

Your email address will not be published. Required fields are marked *