I'm struggling with figuring out how to mock a callback function and the function that calls it. The specific function I'm trying to mock is "listenOnAMessageWithCallBack" from a service I'm injecting, along with the callback function it triggers.
Here is my current implementation:
async getUsername(): Promise<string> {
return await new Promise<string>((resolve, reject) => {
try {
this.electronController.sendMessage('userName');
let cb = (event, username) =>{
this.username = username;
let user = this.stripDomain(this.username);
resolve(user);
};
this.electronController.listenOnAMessageWithCallBack('catchUser', cb);
} catch (err) {
reject(err);
}
})
}
And here's the test setup:
it('testing function with callback', async() => {
const stripDomain = spyOn(service, 'stripDomain').and.callFake(()=>{
service.username = service.username.split('\\').reverse()[0];
return service.username;
});
let cb = (event, username)=>{Promise.resolve('username')}
spyOn(electronController, 'listenOnAMessageWithCallBack').withArgs('message').and.callFake(()=>{});
let username = await service.getUsername();
expect(username).toBe('username');
expect(stripDomain).toHaveBeenCalledTimes(1);
});
When running the test, I encounter the following error message: "Spy 'listenOnAMessageWithCallBack' received a call with arguments [ 'catchUser', Function ] but all configured strategies specify other arguments."
If anyone has insights on how to properly mock the callback function and its caller, your help would be greatly appreciated. Thank you!