I’ve recently found myself writing tests frequently with modern Angular applications utilising the newer Angular features - one of those significant features being standalone components.
There isn’t a great deal of changes involved here, but there are some specific new challenges with standalone components. Most notably that a standalone component supplies its own imports
.
So… what if we want to mock one of the components imports? We can’t just do that in the testing module now, we need to alter the component itself. This is easy enough to do, and I created this snippet for my editor to make this easier:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [MyComponent],
})
.overrideComponent(MyComponent, {
remove: { imports: [] },
add: { imports: [] },
})
.compileComponents();
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
This is largely the same as a typical TestBed set up, except this overrideComponent
section:
.overrideComponent(MyComponent, {
remove: { imports: [] },
add: { imports: [] },
})
This allows you to easily remove an import from the component being tested, and supply others. This would allow you to swap out a component with a mock of that component for example:
.overrideComponent(MyComponent, {
remove: { imports: [SomeComponent] },
add: { imports: [MockSomeComponent] },
})