Good evening,
I am currently in the process of developing tests for the TypeScript class shown below. My goal is to create a test that ensures the postMessage
method of the internal BroadcastChannel
is called. However, I am facing difficulties in setting up the appropriate spy for this task. It seems like the issue lies in not properly attaching the spy to the actual instance within the class, but I'm uncertain about how to resolve it.
export class BroadcastChannelService<T> {
private readonly broadcastChannel: BroadcastChannel;
constructor(name: CHANNEL_NAMES) {
this.broadcastChannel = new BroadcastChannel(name);
}
postMessage = (msg: T) => {
this.broadcastChannel.postMessage(msg);
}
}
Below is the current state of the test that I have developed:
import { BroadcastChannel } from 'broadcast-channel';
import { BroadcastChannelService } from '../../services';
jest.mock('broadcast-channel');
const mockedBroadcastChannel = BroadcastChannel as jest.Mocked<typeof BroadcastChannel>;
describe('BroadcastChannelService', () => {
let subject: BroadcastChannelService<string>;
describe('constructor', () => {
afterAll(() => {
jest.resetAllMocks();
});
test('is successful', () => {
// eslint-disable-next-line no-unused-vars
subject = new BroadcastChannelService<string>('GOOGLE_AUTH');
expect(mockedBroadcastChannel).toBeCalledWith('GOOGLE_AUTH');
expect(mockedBroadcastChannel).toBeCalledTimes(1);
});
});
describe('postMessage', () => {
beforeAll(() => {
subject = new BroadcastChannelService('GOOGLE_AUTH');
subject.postMessage('Hello World');
});
afterAll(() => {
jest.resetAllMocks();
});
test('is successful', () => {
});
});
});