【问题标题】:Electron-Angular: Running Karma errors because of undefined ipcRenderer inside angular componentElectron-Angular:由于角度组件内未定义的 ipcRenderer 导致运行 Karma 错误
【发布时间】:2020-02-15 06:01:45
【问题描述】:

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

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 组件进行单元测试?

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

【问题讨论】:

    标签: angular unit-testing electron karma-jasmine ipcrenderer


    【解决方案1】:

    您应该模拟电子服务并在您的提供程序中使用Class: 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();
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-20
      • 1970-01-01
      • 1970-01-01
      • 2013-04-26
      • 1970-01-01
      • 2017-01-12
      • 1970-01-01
      相关资源
      最近更新 更多