簡體   English   中英

使用 Karma Jasmine 在 Angular 的單元測試中無法讀取未定義的屬性“on”

[英]Getting Cannot read property 'on' of undefined in Unit Testing in Angular using Karma Jasmine

在我的 component.ts 文件中,我有一個名為“socketService”的服務,我在其中使用套接字,在組件中,我有一行

this.socket = this.socketService.getSocketIOConnector(this.data.product)
this.socket.on('connected', (message: string) => {
    this.connectionMsg = message
})

在我的 spec.ts 文件中,我有

beforeEach(async(() => {
  fixture = TestBed.createComponent(OndemandComponent);
  component = fixture.componentInstance;
  fixture.detectChanges();
}));
it("should check socket service", inject([SocketioService], (socketioService: SocketioService) => {
  socketioService = TestBed.get(SocketioService);
  const spy = spyOn(socketioService, "getSocketIOConnector");
  expect(spy).toHaveBeenCalled();
}));
it("should create", () => {
  expect(component).toBeTruthy();
});

它給了我 TypeError: Cannot read property 'on' of undefined 在組件中的 this.socket.on 附近進行測試時。

您沒有模擬getSocketIOConnector方法的返回值。 這就是你得到錯誤的原因。 此外,您需要調用fixture.detectChanges(); 在 mock 之后觸發組件的ngOnInit方法。

這是使用angular v11+ 的工作示例:

ondemand.component.ts

import { Component, OnInit } from '@angular/core';
import { SocketService } from './socket.service';

@Component({})
export class OndemandComponent implements OnInit {
  socket: SocketService;
  data = {
    product: 'real product',
  };
  connectionMsg: string;
  constructor(private socketService: SocketService) {}
  ngOnInit() {
    this.socket = this.socketService.getSocketIOConnector(this.data.product);
    this.socket.on('connected', (message: string) => {
      this.connectionMsg = message;
    });
  }
}

socket.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class SocketService {
  getSocketIOConnector(params) {
    return this;
  }
  on(event, listener) {}
}

ondemand.component.spec.ts

import { ComponentFixture, inject, TestBed } from '@angular/core/testing';
import { OndemandComponent } from './ondemand.component';
import { SocketService } from './socket.service';

fdescribe('65302152', () => {
  let fixture: ComponentFixture<OndemandComponent>;
  let component: OndemandComponent;
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [OndemandComponent],
      providers: [SocketService],
    }).compileComponents();
    fixture = TestBed.createComponent(OndemandComponent);
    component = fixture.componentInstance;
  });
  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should check socket service', inject(
    [SocketService],
    (socketioService: SocketService) => {
      const connectorSpy = jasmine.createSpyObj('connector', ['on']);
      connectorSpy.on.and.callFake((event, listener) => {
        listener('fake message');
      });
      const getSocketIOConnectorSpy = spyOn(
        socketioService,
        'getSocketIOConnector'
      ).and.returnValue(connectorSpy);

      // trigger ngOnInit of component
      fixture.detectChanges();

      expect(getSocketIOConnectorSpy).toHaveBeenCalledOnceWith('real product');
      expect(connectorSpy.on).toHaveBeenCalledOnceWith(
        'connected',
        jasmine.any(Function)
      );
    }
  ));
});

單元測試結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM