我打开了一个在构造函数对话框内部使用的组件,如下所示:
dialog = inject( MatDialog );
constructor () {
this.dialog.open( WelcomeComponent , {
width:'350px',
height:'350px'
} );
我不知道如何测试是否打到了open
.我面临的问题是,组件是在jest.spyOn
对象之前创建的,这导致在try 时调用0:
it( 'open welcome dialog', () => {
const openDialogSpy = jest.spyOn( TestBed.inject(MatDialog), 'open' );
expect( openDialogSpy ).toHaveBeenCalled();
//I know this code leads to nothing but it's just an example
})
编辑:
以下是我到目前为止的测试:
import { ElementRef } from '@angular/core';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MatDialog, MatDialogModule } from '@angular/material/dialog';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import { AppComponent } from './app.component';
import { MediaService } from './services/media.service';
import { WelcomeComponent } from './welcome/welcome.component';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports:[AppComponent, NoopAnimationsModule, MatDialogModule ],
providers:[
{ provide:ElementRef, useValue:{}},
{ provide:MediaService, useValue:{}},
{ provide:MatDialog },
]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it( 'open welcome dialog', () => {
const dialogSpy = jest.spyOn(component.dialog, 'open')
component.dialog.open( WelcomeComponent , {
width:'350px',
height:'350px'
} );
expect( dialogSpy ).toHaveBeenCalledTimes(1);
})
});