运行jasmine测试用例后出错: - TypeError:this.snackBarRef.dismiss不是函数

问题描述 投票:2回答:1

我在运行测试用例后遇到错误。下面是我的ts文件。

    import { Component, OnInit, Inject} from '@angular/core';
    import { MAT_SNACK_BAR_DATA } from '@angular/material';
    import { MatSnackBarRef } from '@angular/material';

    @Component({
        selector: 'Message',
        templateUrl: './Message.component.html',
        styleUrls: ['./Message.component.scss'],
    })
    export class MessageComponent implements OnInit {
        constructor(
            @Inject(MAT_SNACK_BAR_DATA) public data: any,
            public snackBarRef: MatSnackBarRef<MessageComponent>
        ) {}

        ngOnInit() {}

        dismiss(): void {
            this.snackBarRef.dismiss();
        }
    }

我收到以下错误 - TypeError:this.snackBarRef.dismiss不是一个函数

我已经监视了下面的功能 -

describe('MessageComponent', () => {
let component: MessageComponent;
let fixture;

beforeEach(() => {
    TestBed.configureTestingModule({
        providers: [{ provide: MAT_SNACK_BAR_DATA, useValue: {} }, { provide: MatSnackBarRef, useValue: {} }],
        declarations: [MessageComponent],
    });

    fixture = TestBed.createComponent(MessageComponent);
    component = fixture.componentInstance;
    spyOn(component, 'dismiss').and.callThrough();
});
it('should call dismiss function', () => {
    component.dismiss();
    expect(component.dismiss).toHaveBeenCalled();
});
});

我需要解决方案来修复此错误。

angular typescript karma-jasmine istanbul
1个回答
2
投票

在测试运行时属性中,组件实例中的snackBarRef为{},因为您在TestBed中声明了它({ provide: MatSnackBarRef, useValue: {} }

你在监视dismiss方法(在测试运行时)。 Dismiss正在调用this.snackBarRef.dismiss,因为testBed this.snackBarRef是{}所以this.snackBarRef.dismiss是未定义的,并且调用它会引发错误。

要解决这个问题,请通过以下方法创建更复杂的snackBarRef模拟{ provide: MatSnackBarRef, useValue: { dismiss: () => {} } }。在那种情况下,测试不会崩溃。

也将很好地监视this.snackBarRef.dismiss并检查是否被调用。

© www.soinside.com 2019 - 2024. All rights reserved.