【问题标题】:How to write a unit test for a mat dialog using jasmine and Angular 7?如何使用 jasmine 和 Angular 7 为 mat 对话框编写单元测试?
【发布时间】:2020-02-18 03:13:14
【问题描述】:

我正在为打开 mat 对话框的组件中的方法编写单元测试。尝试编写以下单元测试以确保对话框是否打开。但是我遇到了一个错误。

component.ts:

它有onupload方法。

    onUpload(event: FileUpload) {
        this.Service
            .get(event.id)
            .subscribe((data: Data[]) => {
                const dialogRef = this.dialog.open(
                    DialogComponent,
                    {data,}    
                );

                dialogRef.afterClosed().subscribe({
                    next: (Id: string) => {
                        if (Id === null {
                            this.reset();
                        }

unittest.spec.ts:

    describe('open()', () => {
        it('should open the dialog', () => {
            const testCases = [
                {
                    returnValue: 'Successfully opens a dialog',
                    isSuccess: true
                },
                {
                    returnValue: 'cancel',
                    isSuccess: false
                },
            ];

            testCases.forEach(testCase => {
                it(`should open the file upload matDialog `, () => {
                    const returnedVal = {
                        afterClosed: () => of(testCase.returnValue)
                    };
                    spyOn(component, 'reset');
                    spyOn(component['matDialog'], 'open').and.returnValue(returnedVal);
                    component.onUpload(new FileUpload(
                        'fid',
                        'oid',
                    ));

                    if (testCase.isSuccess) {
                        expect(component.reset).toHaveBeenCalled();
                    } else {
                        expect(component.reset).not.toHaveBeenCalled();
                    }

                    expect(component['matDialog'].open).not.toHaveBeenCalled();
                });
            });

我收到一个错误“'mat-grid-tile' 不是已知元素: 1. 如果 'mat-grid-tile' 是 Angular 组件,则验证它是否是该模块的一部分。”。请帮忙。谢谢。

【问题讨论】:

  • 确保在配置测试模块时导入MatGridListModule (TestBed.configureTestingModule)。
  • @uminder 导入了 MatGridListModule。为那个错误工作。现在得到 "Error: 'it' should only be used in 'describe' function" 。我是否以正确的方式编写测试(我的意思是它应该在茉莉花中并且逻辑上也很明智?

标签: unit-testing jasmine angular7 karma-jasmine


【解决方案1】:

“错误:'it' 只能用于 'describe' 函数” 与嵌套的 it 函数有关。如果您删除封闭的it 语句,您应该摆脱错误。

describe('open()', () => {
    // it('should open the dialog', () => { // get rid of this
    const testCases = [
    ...

【讨论】:

  • 解决了这个问题。非常感谢。请让我知道如何监视 matdialog 元素吗?我现在收到“错误::找不到用于监视 open() 的对象”。
  • @Mia 你介意我的回答,至少解决了你的问题吗?
  • 我认为我没有权限。:(
猜你喜欢
  • 2023-03-06
  • 1970-01-01
  • 2018-12-11
  • 2021-09-02
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 2016-06-29
  • 2023-03-24
相关资源
最近更新 更多