在不引用其他嵌套组件的情况下测试Angular组件

时间:2019-08-07 08:58:51

标签: angular jasmine

我不会包含太多代码,因为它会使理解变得过于复杂

我是Angular的新手,并且是单元测试框架Jasmine的新手。因此,在我的Angular应用程序中,我有一个组件Test-Table-component,该组件使用/引用Angular的材料表,要求它引用MatDialogRef, MatDialogModule等,等等。

该组件还使用HttpClient,因为它对我们的WebAPI进行了REST调用。

无论如何,我想现在该咒骂Jasmine了。因此,首先,我创建一个测试文件来测试我的组件:test-table.component.spec.ts。我遵循了文档和一些建议,最后得到了一些代码。在添加代码之前,让我解释一下这个问题。由于我的Test-table组件依赖于其他组件/依赖项,因此我需要将每个组件/依赖项都引用到测试类中,这似乎是一项巨大的工作。我尝试应用No_Errors_Schema技巧,但随后我遇到了很多其他异常,这再次要求我引用所有其他依赖项,这又导致其他错误。

这就是我现在拥有的:

 describe('TestTableComponent',  async() => 
{
const mockDialogRef = {
    close: jasmine.createSpy('close')
};
let component: TestTableComponent;
let fixture: ComponentFixture<TestTableComponent>;
let de: DebugElement;


beforeEach(async(() => 
{
    TestBed.configureTestingModule({declarations:[TestTableComponent],
        imports: [ReactiveFormsModule, MatTableModule, FormsModule, HttpClientModule],
        schemas: [NO_ERRORS_SCHEMA], providers: [{
            provide: MatDialogRef,
            useValue: mockDialogRef
        }]
    }).compileComponents();
}));
beforeEach(() =>
{

    fixture = TestBed.createComponent(TestTableComponent);
    component = fixture.componentInstance;

    de = fixture.debugElement;
})


it('should check if data is returned by the API', async(() =>{
    fixture.detectChanges();
    const result = component.GetEmployees();
    fixture.whenStable().then(()=>{
    expect(result).toBeDefined();
    })
}))
});

现在会抛出:

  

StaticInjectorError(平台:核心)[TestTableComponent-> MatDialog]:       NullInjectorError:MatDialog没有提供程序!

所以最后,我如何仅测试GetEmployees()函数,而不必引用所有其他依赖项?

0 个答案:

没有答案