无法读取未定义的属性“endsWith”

时间:2020-12-30 23:40:52

标签: angular karma-jasmine

我正在尝试为我的组件编写我的第一个单元测试,但发现以下问题:

TypeError: Cannot read property 'endsWith' of undefined. 

如何在测试中声明 data.iconPath 以消除错误?

这是我的组件:

import {Component, Inject, ViewEncapsulation} from '@angular/core';
import {MAT_SNACK_BAR_DATA, MatIconRegistry, MatSnackBar, MatSnackBarRef} from "@angular/material";
import {DomSanitizer} from "@angular/platform-browser";

@Component({
  selector: 'app-custom-snackbar',
  templateUrl: './custom-snackbar.component.html',
  styleUrls: ['./custom-snackbar.component.scss'],
  encapsulation: ViewEncapsulation.None
})
export class CustomSnackbarComponent {
  public readonly isSvgIcon: boolean;

  constructor(@Inject(MAT_SNACK_BAR_DATA) public data: any, public _snackBarRef: MatSnackBarRef<CustomSnackbarComponent>, iconRegistry: MatIconRegistry, sanitizer: DomSanitizer) {
  this.isSvgIcon = data.iconPath.endsWith('.svg');
    if (this.isSvgIcon) {
      iconRegistry.addSvgIcon(
        data.snackBarType,
        sanitizer.bypassSecurityTrustResourceUrl(data.iconPath));
    }
  }

  close = () => {
    this._snackBarRef.dismiss();
  }

}

这是我的测试:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { CustomSnackbarComponent } from './custom-snackbar.component';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { MatSnackBarModule, MAT_DIALOG_DATA, MAT_SNACK_BAR_DATA, MatSnackBarRef } from '@angular/material';

describe('CustomSnackbarComponent', () => {
  let component: CustomSnackbarComponent;
  let fixture: ComponentFixture<CustomSnackbarComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ CustomSnackbarComponent ],
      imports: [  MatSnackBarModule, ] ,
      providers: [ { provide: MAT_SNACK_BAR_DATA, useValue: {} },
                   { provide: MatSnackBarRef, useValue: {} }],
      schemas:      [ CUSTOM_ELEMENTS_SCHEMA ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CustomSnackbarComponent);
    component = fixture.componentInstance;
    component.data.iconPath = '123.svg';
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

如果您能帮助解决此问题,我们将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:0)

这里你提供的是一个空的配置

{ provide: MAT_SNACK_BAR_DATA, useValue: {} }

相反,提供不会使您的代码失败的对象

{ provide: MAT_SNACK_BAR_DATA, useValue: {iconPath: 'path.to.icon'} }