I have an Electron application that uses Angular (8) as a front end framework. I am trying to implement unit testing but keep getting the following error when i start the test:
Chrome 77.0.3865 (Windows 10.0.0) FooterComponent should create FAILED
TypeError: Cannot read property 'on' of undefined
......
My spec file looks like this:
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();
});
});
Inside the Angular component i subscribe to an Electron event:
constructor(private electronService: ElectronService) {
this.electronService.ipcRenderer.on('appVersion', (event, arg) => {
this.appVersion = arg;
});
}
This is what causes the test to fail, the ipcRenderer is undefined. Does anyone know how i can unit test an Angular component that has Electrons IPC used inside of it ?
The electronservice that is used in the component has been added to the providers inside the spec file.
You should mock the electron service and in your providers 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();
});
}
}