gpt4 book ai didi

angular - Electron Angular : Running Karma errors because of undefined ipcRenderer inside angular component

转载 作者:行者123 更新时间:2023-12-03 12:24:13 25 4
gpt4 key购买 nike

我有一个使用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未定义。有谁知道我该如何对其中使用了Electron IPC的Angular组件进行单元测试?

组件中使用的 Electron 服务已添加到spec文件中的提供程序。

最佳答案

您应该模拟 Electron 服务,并在您的提供者中使用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();
});
}
}

关于angular - Electron Angular : Running Karma errors because of undefined ipcRenderer inside angular component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58447470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com