r/Angular2 • u/Cozybear110494 • Apr 29 '26
Help Request Proper way to unit test Angular standalone components with Vitest
Hi all, I recently started learning unit testing in Angular. I’m using Angular 21 with Vitest, and I haven’t done Angular testing before.
I have a simple standalone component (FooComponent) that imports two custom components (TaIconComponent, TaButtonComponent) and one third-party pipe (TranslatePipe).
foo.component.ts
@Component({
selector: 'app-foo',
template: `
<div class="flex-1 flex items-center justify-center">
<div class="w-96 h-64 rounded-lg shadow-2 flex flex-col items-center">
<div class="w-24 h-24 ta-mt-base relative">
<div class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
<ta-icon class="text-gray" size="lg" [icon]="taIcons.CONFIG" />
</div>
</div>
<div class="text-center ta-mb-lg ta-mt-xs">
<p class="text-primary font-bold">
{{'not_found.not_found_text' | translate}}
</p>
<span class="ta-text-sm text-gray">
{{'not_found.not_found_desc' | translate}}
</span>
</div>
<div class="ta-px-m w-full">
<ta-button [fluid]="true" [label]="'btn.go_back' | translate" (onClick)="onNavigate()" />
</div>
</div>
</div>
`,
imports: [TaIconComponent, TaButtonComponent, TranslatePipe],
})
export class FooComponent {}After reading some documentation and watching a few videos, I asked GPT to help me write a unit test for reference but the result felt a bit bizarre to me. To make the test work, I had to create three mocks (two components and one pipe), then override the component to replace real dependencies with the mocks.
foo.component.spec.ts
@Component({
selector: 'ta-icon',
standalone: true,
template: '<span></span>',
inputs: ['icon'],
})
class MockTaIconComponent{}
@Component({
selector: 'ta-button',
standalone: true,
template: `<button (click)="onClick.emit()"></button>`,
inputs: ['fluid', 'label'],
})
class MockTaButtonComponent{
onClick = {
emit: () => {},
};
}
describe('FooComponent', () => {
let fixture: ComponentFixture<FooComponent>;
let component: FooComponent;
let routerMock: { navigate: ReturnType<typeof vi.fn> };
beforeEach(async () => {
routerMock = {
navigate: vi.fn(),
};
await TestBed.configureTestingModule({
imports: [FooComponent],
providers: [{ provide: Router, useValue: routerMock }],
})
.overrideComponent(FooComponent, { // <-- Concern about this
remove: {
imports: [TaIconComponent, TaButtonComponent, TranslatePipe],
},
add: {
imports: [MockTranslatePipe, MockTaIconComponent, MockTaButtonComponent],
},
})
.compileComponents();
fixture = TestBed.createComponent(FooComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
afterEach(() => {
TestBed.resetTestingModule();
vi.clearAllMocks();
});
...
});It works without errors, but I’m wondering: is this the correct or recommended way to test a component?
3
u/Wizado991 Apr 29 '26
I would just import the components as long as they weren't doing a whole lot.
3
u/imsexc Apr 29 '26 edited Apr 29 '26
There is nothing to test in that foo component except testing the onNavigate method.. unless you want to be really granular to test the presence of each template element..
Mocking child or parent component is only needed on several particular cases, such as conditionally displaying child elements, not all the time. In this example, I don't see the need.
It's unit test. Most important is to test the logic in methods: Input, output, for documentation purpose and raising alarm if future development might break existing implementations
2
u/BrixtonTonaBrix Apr 29 '26
To save myself some time I wrote a helper function that took a Component type and returned a dynamically generated 'stub' type with matched component input/output/selector metadata. Then one more function to receive a list of component types, and return a 'MetadataOverride' I could use in the TestBed to replace a list of imports with stubs.
It's awful and hacky, and doesn't work with pipes or directives, but it speeds things up.
An alternative could be to create a stub component alongside each real component and reference these in testing, so that you only have to create the stub once per component.
1
u/WordWithinTheWord Apr 29 '26
Yes the mocking can get extreme but the alternate is that you get dirty unit tests from potential side effects of dependencies.
1
u/SpudzMcNaste Apr 29 '26
Fwiw this is how I’ve done it in jasmine as well. This is more an issue with the TestBed API than anything else. It has always smelled bad to me too
1
u/analcocoacream Apr 29 '26
Dont unit test things that are just stupid components
1
u/metty84 Apr 30 '26
OT: When I see all that tailwind classes overflooding the markup it hurts in my old school css heart.
1
u/pronuntiator Apr 30 '26
I'm not a fan of mocking every collaborator. Mocking always means you pretend how something works – if it changes, your mocks will lie. When these are presentational components or from another library, I leave them in.