1

我有一个使用 Angular (8) 作为前端框架的电子应用程序。我正在尝试实施单元测试,但在开始测试时不断收到以下错误:

Chrome 77.0.3865 (Windows 10.0.0) FooterComponent should create FAILED
        TypeError: Cannot read property 'on' of undefined
         ......

我的规范文件如下所示:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { FooterComponent } from './footer.component';
import { TranslateModule } from '@ngx-translate/core';
import { ElectronService } from '../services';


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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ 
        FooterComponent
      ],
      providers: [ElectronService ],
      imports: [
        TranslateModule.forRoot()
      ]
    })
    .compileComponents();
  }));

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

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

});

在 Angular 组件中,我订阅了一个 Electron 事件:

constructor(private electronService: ElectronService) {
   this.electronService.ipcRenderer.on('appVersion', (event, arg) => {
      this.appVersion = arg;
   });
}

这就是导致测试失败的原因,ipcRenderer 未定义。有谁知道我如何对内部使用 Electrons IPC 的 Angular 组件进行单元测试?

组件中使用的电子服务已添加到规范文件中的提供程序中。

4

1 回答 1

2

您应该模拟电子服务并在您的提供者中使用类:MockElectronService

class Channel {
  constructor(public name: string, public listener: () => {}) {}
}

export class Message {
  channel: string;
  params?: any[];
}

export class MockElectronService {
  channelSource = new Subject<Message>();

  private channels: Channel[] = [];

  ipcRenderer = {
    on: (name: string, listener: () => {}) => {
      this.channels.push(new Channel(name, listener));
    },
    once: (name: string, listener: () => {}) => {
      this.channels.push(new Channel(name, listener));
    },
    send: (channel: string, args: string) => {}
  };

  constructor() {
    this.channelSource.subscribe(msg => {
      this.channels.find(channel => channel.name === msg.channel).listener();
    });
  }
}
于 2020-03-13T19:42:41.363 回答