1

我正在尝试编写一个 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 处的依赖无效。

这里有什么问题?

4

0 回答 0