StaticInjectorError(DynamicTestModule)[MatTable-> ChangeDetectorRef]:StaticInjectorError(Platform:core)[MatTable-> ChangeDetectorRef]:NullInjectorError:ChangeDetectorRef没有提供者!
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MessagesComponent } from './messages.component';
import { NgModule,CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA} from '@angular/core';
import { MatTableModule } from '../../../MessageUtility/node_modules/@angular/material';
import { HttpClientModule } from '@angular/common/http';
import { RouterTestingModule } from '@angular/router/testing';
describe('MessagesComponent', () => {
let component: MessagesComponent;
let fixture: ComponentFixture<MessagesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ MessagesComponent ],
imports:[HttpClientModule,RouterTestingModule,MatTableModule, ],
schemas: [NO_ERRORS_SCHEMA,NO_ERRORS_SCHEMA]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MessagesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
答案 0 :(得分:1)
另一种方法是在 ChangeDetectorRef
声明中提供所有必需的 TestBed.configureTestingModule
方法。
例如,如果您的代码(或像您的案例中的第三个库)使用 detectChanges
实例的 ChangeDetectorRef
方法,您可以按以下示例提供它:
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
// other providers here
{ provide: ChangeDetectorRef, useValue: { detectChanges: () => { } } }
]
});
});
答案 1 :(得分:0)
您是否使用ChangeDetectionStrategy.OnPush
作为变更检测策略?正如here所述,ChangeDetectorRef实际上已暴露在灯具中。
如果已将ChangeDetectorRef定义为组件中的私有属性之一,如下所示:
constructor(private cdr: ChangeDetectorRef) { }
由于它是私有的,因此应该在测试文件中为该属性创建一个间谍作为存根,并测试是否正在调用ChangeDetectorRef。只需执行以下操作即可在您的.spec文件上模拟CDR:
it('test CDR', () => {
const spyCDR = spyOn((component as any).cdr, 'detectChanges');
component.method();
expect(spyCDR).toHaveBeenCalled();
});