简体   繁体   English

使用 Jest Mat 分页器测试用例的角度单元测试失败:- TypeError:无法读取未定义的属性“页面”

[英]Angular unit testing with Jest Mat paginator test case getting failed :- TypeError: Cannot read property 'page' of undefined

I have a component which uses Mat paginator for pagination purpose, the component is working fine but while running the command npx jest -- layout.component.spec.ts (I am are using jest framework)the below test case is getting failed with below is the error.我有一个使用 Mat paginator 进行分页的组件,该组件工作正常,但是在运行命令npx jest -- layout.component.spec.ts (我正在使用 jest 框架)时,下面的测试用例在下面失败了是错误。

Test Case getting failed :测试用例失败:

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

ERROR :错误

should create (1070ms)

● LayoutComponent › should create ● LayoutComponent › 应该创建

TypeError: Cannot read property 'page' of undefined



  at LayoutComponent.ngAfterViewInit (src/app/modules/adverse-media/card-layout/card-layout.component.ts:2015:20)
  at ngAfterViewInit (node_modules/@angular/core/bundles/core.umd.js:21557:22)
  at callProviderLifecycles (node_modules/@angular/core/bundles/core.umd.js:21531:17)
  at callElementProvidersLifecycles (node_modules/@angular/core/bundles/core.umd.js:21521:33)
  at callLifecycleHooksChildrenFirst (node_modules/@angular/core/bundles/core.umd.js:29563:9)
  at apply (node_modules/@angular/core/bundles/core.umd.js:30424:29)
  at Object.callWithDebugContext [as checkAndUpdateView] (node_modules/@angular/core/bundles/core.umd.js:30126:16)      at ViewRef_.checkAndUpdateView [as detectChanges] (node_modules/@angular/core/bundles/core.umd.js:20829:26)     
  at ComponentFixture._tick (../../packages/core/testing/src/component_fixture.ts:107:28)
  at ../../packages/core/testing/src/component_fixture.ts:120:36
  at ZoneDelegate.apply [as invoke] (node_modules/zone.js/dist/zone.js:391:26)
  at ProxyZoneSpec.invoke [as onInvoke] (node_modules/zone.js/dist/proxy.js:129:39)
  at ZoneDelegate.onInvoke [as invoke] (node_modules/zone.js/dist/zone.js:390:52)
  at Object.invoke [as onInvoke] (node_modules/@angular/core/bundles/core.umd.js:26371:37)
  at ZoneDelegate.onInvoke [as invoke] (node_modules/zone.js/dist/zone.js:390:52)
  at Zone.invoke [as run] (node_modules/zone.js/dist/zone.js:150:43)
  at NgZone.run (node_modules/@angular/core/bundles/core.umd.js:26285:32)
  at ComponentFixture.detectChanges (../../packages/core/testing/src/component_fixture.ts:120:19)
  at src/app/modules/adverse-media/card-layout/card-layout.component.spec.ts:55:13
  at ZoneDelegate.apply [as invoke] (node_modules/zone.js/dist/zone.js:391:26)
  at ProxyZoneSpec.invoke [as onInvoke] (node_modules/zone.js/dist/proxy.js:129:39)
  at ZoneDelegate.onInvoke [as invoke] (node_modules/zone.js/dist/zone.js:390:52)
  at Zone.invoke [as run] (node_modules/zone.js/dist/zone.js:150:43)

Component Code / usage of paginator:分页器的组件代码/用法:

@ViewChild(MatPaginator, { static: true }) paginator: MatPaginator;

ngAfterViewInit(): void {
    this.paginator.page.subscribe(() => {
      this.characterDatabase
        .getCharacters("", "", this.paginator.pageIndex)
        .subscribe((response: HttpRequest) => {
          this.characterDataSource = new MatTableDataSource(
            response.results as any[]
          );
          this.resultsLength = response.info.count;
          this.characters$ = this.characterDataSource.connect();
        });
    });
  }

Definition of page being used in the ngAfterViewInit here this.paginator.page.subscribe ngAfterViewInit 中使用的页面定义在这里this.paginator.page.subscribe

 paginator.d.ts
   /** Event emitted when the paginator changes the page size or page index. */
    readonly page: EventEmitter<PageEvent>;

Spec.ts File Code :- Spec.ts 文件代码:-

import { HttpClientTestingModule } from "@angular/common/http/testing";
import { ViewChild } from "@angular/core";
import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import {
  MatCardModule,
  MatChipsModule,
  MatIconModule,
  MatPaginator,
  MatPaginatorModule,
  MatSortModule,
  MatTableModule,
  PageEvent,
} from "@angular/material";
import { BrowserAnimationsModule } from "@angular/platform-browser/animations";
import { PipesModule } from "@app/shared/pipes/pipes.module";   
import { LayoutComponent } from "./card-layout.component";

describe("LayoutComponent", () => {
  let component: LayoutComponent;
  let fixture: ComponentFixture<LayoutComponent>;

  //let someServiceMock;

  beforeEach(async(() => {

    TestBed.configureTestingModule({
      declarations: [LayoutComponent],
      imports: [
        PipesModule,
        PipesModule,
        MatCardModule,
        MatChipsModule,
        MatPaginatorModule,
        MatIconModule,
        HttpClientTestingModule,
        MatTableModule,
        MatSortModule,
        BrowserAnimationsModule,
      ],
      providers: [{ provide: MatPaginator, useValue: MatPaginator }],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LayoutComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

What I have tried till now to mock that read only page event emitter :-到目前为止,我一直在尝试模拟只读页面事件发射器:-

 //let someServiceMock;
//const paginator = jasmine.createSpyObj('ChildComponent', ['childMethod']);
    //someServiceMock = {testEmitter: {subscribe: spyOn('testEmitter subscribe')}};

fixture = TestBed.createComponent(CardLayoutComponent);
    component = fixture.componentInstance;

    //Object.defineProperty(component.paginator.page, PageEvent , Writable);
    //spyOn(component.paginator.page, "subscribe").and.returnValue("");
    //spyOn(component.paginator, 'page', 'subscribe').and.returnValue(1);
    //expect(component.paginator.page.emit).toReturn();
    fixture.detectChanges();

it("should create", () => {
    //spyOn(component.paginator.page, "subscribe").and.returnValue("");
    expect(component).toBeTruthy();
  });

something that I have tried from my end, I was not able to post everything what I tried but a help is appreciated as I am much new to jest, i am not able to figure this out.我从头到尾都尝试过的东西,我无法发布我尝试过的所有内容,但是感谢您的帮助,因为我对开玩笑很陌生,我无法弄清楚这一点。 Please let me know how to mock/define this item so that test should pass.请让我知道如何模拟/定义这个项目,以便测试通过。 sorry for typos对不起错别字

The line below is incorrect, it is doing nothing:下面的行不正确,它什么也没做:

providers: [{ provide: MatPaginator, useValue: MatPaginator }],

What I think is happening, is that the pagination component ( @ViewChild() ) is being blocked by an *ngIf and therefore this.paginator does not exist in the ngAfterViewInit hook.我认为正在发生的是分页组件( @ViewChild() )被*ngIf阻塞,因此this.paginator不存在于ngAfterViewInit挂钩中。

For a super quick unblock, try this:要快速解锁,请尝试以下操作:

ngAfterViewInit(): void {
    if (this.paginator) {
      // !! the rest of the logic here
    }
  }

You should also try to find out why this.paginator is undefined (why MatPaginator is not in the HTML) when you unit test.您还应该在单元测试时尝试找出this.paginator未定义的原因(为什么 MatPaginator 不在 HTML 中)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MOCK COLD Observable 的正确方法? 获取类型错误:无法读取未定义的属性“获取” - JEST 单元测试用例 - Angular - Correct way to MOCK COLD Observable ? Getting TypeError: Cannot read property 'get' of undefined - JEST Unit Test Case - Angular 类型错误:无法读取 jasmine 单元测试用例中未定义的属性“nativeElement” - TypeError: Cannot read property 'nativeElement' of undefined in jasmine unit test case Angular 测试笑话 - 类型错误:无法读取未定义的属性“queryParams” - Angular Test Jest - TypeError: Cannot read property 'queryParams' of undefined TypeError:在单元测试Angular 6时无法读取未定义的属性“查询” - TypeError: Cannot read property 'query' of undefined while unit testing Angular 6 角度单元测试TypeError:无法读取未定义的属性“订阅” - Angular unit testing TypeError: Cannot read property 'subscribe' of undefined Angular 单元测试:TypeError:无法读取未定义的属性“根” - Angular unit Testing : TypeError: Cannot read property 'root' of undefined AfterAll TypeError:无法读取未定义的属性“isCompleted” - Angular 单元测试 - AfterAll TypeError: Cannot read property 'isCompleted' of undefined - Angular unit testing TypeError:无法在单元测试角度应用程序上读取未定义的属性“subscribe” - TypeError: Cannot read property 'subscribe' of undefined on unit testing angular app Angular 8 - 单元测试问题类型错误:无法读取未定义的属性“名称” - Angular 8 - Unit Test Issue TypeError: Cannot read property 'name' of undefined TypeError:无法读取未定义的属性“ subscribe”(角度单元测试) - TypeError: Cannot read property 'subscribe' of undefined (Angular Unit-Test)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM