Angular 单元测试:此构造函数与 Angular 依赖注入不兼容

问题描述

我正在尝试编写 Angular 单元测试(使用 Angular 测试库)并遇到一个奇怪的错误。 这是我要测试的组件:

import { Component,Inject,OnInit } from '@angular/core';
import { MatDialogRef,MAT_DIALOG_DATA } from '@angular/material/dialog';

@Component({
  selector: 'dtu-alert-dialog',templateUrl: './alert-dialog.component.html',styleUrls: ['./alert-dialog.component.css'],})
export class AlertDialogComponent implements OnInit {
  data: AlertData;
  constructor(
    public dialogRef: MatDialogRef<AlertDialogComponent>,@Inject(MAT_DIALOG_DATA) _data: AlertData
  ) {
    this.data = _data;
  }

  onButtonClick(): void {
    this.dialogRef.close();
  }
  ngOnInit() {}
}

export interface AlertData {
  title?: string;
  content: string;
  buttonLabel?: string;
  width?: string;
}

这是我的测试:

/* tslint:disable:no-unused-variable */
import {
  MatDialogModule,MatDialogRef,MAT_DIALOG_DATA,} from '@angular/material/dialog';
import { fireEvent,render,screen } from '@testing-library/angular';
import { AlertDialogComponent } from './alert-dialog.component';

let clickCounter = 0;

describe('AlertDialogComponent',() => {
  test('should close on button click',async () => {
    const closeFn = jest.fn();
    await render(AlertDialogComponent,{
      imports: [MatDialogModule],providers: [
        {
          provide: MatDialogRef,useValue: {
            close: closeFn,},{
          provide: MAT_DIALOG_DATA,useValue: { content: 'Yankee invasion' },],});

    const closeButton = screen.getByText('Ok');
    fireEvent.click(closeButton);

    expect(closeFn.mock.calls.length).toEqual(1);
  });
});

运行此测试时收到的消息:

此构造函数与 Angular 依赖注入不兼容 因为它在参数列表索引 0 处的依赖是无效的。

这里出了什么问题?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)