我将所有 Angular 组件转换为独立组件。但是,我的单元测试遇到了问题。之前有效的测试现在失败了。
我尝试将模拟组件传递给父级,但父级总是渲染原始组件,而不是我想要的模拟。
示例:
@Component({
selector: 'app-root',
template: '<h2>Hello{{title}}</h2><app-table></app-table>',
styleUrls: ['./app.component.css'],
standalone: true,
imports: [CommonModule, TableComponent],
})
export class AppComponent {
title = 'CodeSandbox';
}
表.组件.ts
@Component({
selector: 'app-table',
template: '<h1>Original Table {{text}}</h1>',
standalone: true,
})
export class TableComponent {
text = 'CodeSandbox';
}
app.component.spec.ts
describe('AppComponent', () => {
let component: LanesComponent;
let fixture: ComponentFixture<LanesComponent>;
let mockTableComponent: jasmine.SpyObj<TableComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent, mockTableComponent],
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should render the mock table', () => {
const tableComponent: MockTableComponent = fixture.debugElement.query(By.directive(MockTableComponent)).componentInstance;
});
});
如果我调试fixture.debugElement正在渲染
<h1>Original Table {{text}}</h1>
,我的mockTable只有一个<h2>Hi</h2>
。如何强制 AppComponent 渲染模拟表组件而不是原始表组件?
非常感谢!
您需要删除原始导入,然后导入模拟组件,这可能会解决您的问题。
参考:测试独立组件
describe('AppComponent', () => {
let component: LanesComponent;
let fixture: ComponentFixture<LanesComponent>;
let mockTableComponent: jasmine.SpyObj<TableComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent, mockTableComponent],
})
.overrideComponent(AppComponent, {
remove: { imports: [ TableComponent] },
add: { imports: [ mockTableComponent ] }
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should render the mock table', () => {
const tableComponent: MockTableComponent = fixture.debugElement.query(By.directive(MockTableComponent)).componentInstance;
});
});