I'm trying to write a unit test for a standalone component and mock its dependency. This standalone component has the following content:
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { DemoDirectiveDirective } from './demo-directive.directive';
@Component({
selector: 'app-demo-cmp',
standalone: true,
imports: [CommonModule,DemoDirectiveDirective],
templateUrl: './demo-cmp.component.html',
})
export class DemoCmpComponent implements OnInit {
constructor() {}
ngOnInit(): void {}
}
and DemoDirectiveDirective has this content:
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appDemoDirective]',
standalone: true,
})
export class DemoDirectiveDirective {
constructor(private hostElement: ElementRef) {
this.hostElement.nativeElement.innerHTML += 'Update from directive! ';
}
}
I want to test DemoCmpComponent
like this:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { DemoCmpComponent } from './demo-cmp.component';
describe('DemoCmpComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [DemoCmpComponent],
}).compileComponents();
});
it('should create', () => {
const fixture = TestBed.createComponent(DemoCmpComponent);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('p').innerHTML).toBe(
'demo-cmp works!'
);
});
});
This test will fail as the the content of the p
tag will be Update from directive! demo-cmp works!
.
What I'm missing here is the step in which I mock DemoDirectiveDirective
which I don't know how to and I don't find any resources for this on Angular page.
Note this is just a demo test, a proof of concept. Please ignore the component names and the superfluous test.
Here is the GitHub repo with the code.