Search code examples
angularunit-testingtypescriptangular-test

unit testing of many simple *ngIf


I have simply component

@Component({
    selector: 'app-certificate-panel',
    templateUrl: './certificate.component.html'
})
export class CertificateComponent {
    @Input()
    public certificate: Certificate;
}

with template

<h3 translate>General</h3>
<x-form-row label="{{'Version' | translate}}">
    {{ certificate.version }}
</x-form-row>
<x-form-row label="{{'Serial Number' | translate}}">
    {{ certificate.serialNumber }}
</x-form-row>
<h3 translate>Issued From</h3>
<x-form-row label="{{'Common Name (CN)' | translate}}" *ngIf="certificate.issuedFrom.commonName">
    {{ certificate.issuedFrom.commonName }}
</x-form-row>
<x-form-row label="{{'Organization Unit (OU)' | translate}}" *ngIf="certificate.issuedFrom.organizationUnit">
    {{ certificate.issuedFrom.organizationUnit }}
</x-form-row>

There are more properties shown. There are several *ngIf in this template.

Now I want to write unit tests. Should I test each *ngIf? Isn't it testing the framework functionality?


Solution

  • There is a range of possible tests you could do with this component:

    1. setup compoenent then query DOM elements to ensure they are present, personally, I don't do these if ngIfs but if it's critial then you have to make the call, it's your app.
    2. since ngIf checks the truthy-ness of the statement, unit test the statement, ie: setup component, check truthy-ness of all those statements. Again, depending on the context, since this is getting data from a parent, you should think about how sure you are that this is going to be populated, program defensively. If there is a chance it could break, just do a cheap test like this.
    3. it's sometimes pointless to test ngIf, like I said in 2, this might be a waste of time since it's going to either be truthy or not so if you can control for that then this component is very simple.
    4. Also you could make a parent test component in the spec to do an integration test, this is very involved but if this component tree is critical or complex, this is often very robust test (Personally would rarely do these).

    The good thing about your component above is that it's simple, and therefore the tests can be simple. I would personally do option 2