angular - 错误 NullInjectorError: R3InjectorError(DynamicTestModule)[KDSDialogService -> MatDialog -> MatDialog]: NullInjectorError: MatDialog 没有提供程序
问题描述
我正在对我的应用程序进行单元测试。我是测试新手,所以我需要你的帮助。
在我的应用程序中,我创建了一个使用 MatDialog(KDSDialogService)的服务。我尝试将许多导入替代品、我的服务或 matdialog 作为提供者我不知道该怎么做
export declare class KDSDialogService {
dialog: MatDialog;
private dialogRef;
constructor(dialog: MatDialog);
open(componentOrTemplateRef: ComponentType<any> | TemplateRef<any>, title?: string, data?: any, size?: DialogSize, showClose?: boolean): MatDialogRef<any, any>;
static ɵfac: ɵngcc0.ɵɵFactoryDef<KDSDialogService, never>;
}
在我的 home.component.spec 中,我在这里导入并声明,但我仍然收到此错误。
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [HomeComponent ],
imports:[KDSDialogService, MatDialogModule],
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
});
it('should create', () => {
fixture.detectChanges();
expect(component).toBeTruthy();
});
});
解决方案
你可以像这样模拟它:
import { MatDialog } from '@angular/material/dialog';
//...
let matDialogService: jasmine.SpyObj<MatDialog>;
matDialogService = jasmine.createSpyObj<MatDialog>('MatDialog', ['open']);
TestBed.configureTestingModule({
providers: [
{
provide: MatDialog,
useValue: matDialogService,
},
推荐阅读
- r - How to get my function to take higher values
- ios - CAAnimation 正在覆盖以前的 CAAnimation 动画
- angular - rxjs中基于布尔可观察的条件可观察转换
- ios - 为什么我的指数不会高于 1?
- angular-material2 - Select All mat option and deselect All
- mariadb - MariaDB 删除临时表的外键
- c++ - Passing pointer to template class object to a function correctly
- python-3.x - 一种热编码:ValueError:无法将字符串转换为浮点数:“是”
- spring-integration - int-jdbc:inbound-channel-adapter channel depth
- haskell - Why do these two functions have a different type?