我有一个使用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组件进行单元测试?
该组件中使用的电子服务已添加到规范文件中的提供程序中。
答案 0 :(得分:2)
您应该嘲笑电子服务,并在提供商中使用useClass: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();
});
}
}