我打开了一个在构造函数对话框内部使用的组件,如下所示:

  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);

  })

});

推荐答案

一旦您连接了jest spyOn,您可以try 重新初始化createComponent

it( 'open welcome dialog', () => {
    const dialogSpy = jest.spyOn(component.dialog, 'open')
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    expect( dialogSpy ).toHaveBeenCalledTimes(1);

})

Angular相关问答推荐

Angular:浏览器中未显示一些Google Content图标

如何在Angular模块中的forRoot中注入配置

日语字符不受角形约束控制

添加@ nx/webpack插件 destruct 了Nativescript构建

如何在投影项目组周围添加包装元素?

try 测试具有Angular material 下拉列表的组件时,在Angular 17中发现&q;错误的意外合成属性@TransitionMessages

如何用ANGLE指令覆盖Html元素的数据绑定属性

我正在try 将一个带有模块联盟的Angular 8项目expose 到另一个Angular 项目,Angular 是15,这可能吗?如果是这样,有什么建议吗?

无法创建新的 Ionic 项目

MAT折叠面板的动态开启和关闭无法工作

从组件调用时服务中的 AddTodo 方法不起作用

使用 RXJS 进行空闲/不活动跟踪

Angular:如何在根组件中使用 ngx-translate?

console.log 返回 api 数据但 ERROR TypeError: Cannot read properties of undefined reading 'name'

as和let之间的异步管道区别

我应该在 Jasmine 3 中使用什么来代替 fit 和 fdescribe?

如何将新的 FormGroup 或 FormControl 添加到表单

Error: Module not found: Error: Can't resolve '@angular/cdk/scrolling'

什么是 Angular 4,我可以从哪里了解更多信息?

Angular 2 - ngfor 没有包装在容器中