Reputation: 79
I'm new to writing unit tests for private methods and I've been researching how to approach this in TypeScript. However, I couldn't find a solution that fits my scenario.
Here's a simplified version of my TypeScript code:
export class CallbackManager {
protected queue: Set<() => void>;
constructor() {
this.queue = new Set();
}
}
export class Report extends CallbackManager {
public addToQueue(publishMetric: () => void): void {
this.queue.add(publishMetric);
}
private flushQueue(): void {
if (this.queue.size > 0) {
this.queue.forEach((cb) => {
cb();
});
this.queue.clear();
}
}
public initializeBatching(): void {
addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
this.flushQueue();
}
});
}
}
Here's what I'm trying to achieve in my tests:
Testing addToQueue method: I want to ensure that calling addToQueue adds a function to the queue.
describe('addToQueue', () => {
it('should add a function to the queue', () => {
const mockFunction = jest.fn();
const report = new Report();
report.addToQueue(mockFunction);
expect((report as any).queue.size).toBe(1); // Accessing protected property directly for testing
});
});
However, I'm encountering this error: Property 'queue' is protected and only accessible within class 'CallbackManager' and its subclasses.
Testing initializeBatching method: I want to verify that the visibilitychange event listener is added when initializeBatching is called. Testing flushQueue method indirectly: I also want to test whether the flushQueue method is called when the visibilitychange event occurs, but flushQueue is a private method. I'd appreciate any insights on how to approach these tests effectively in TypeScript. Thank you!
Upvotes: 0
Views: 66
Reputation: 186
You should be testing that your mock function was called.
expect(mockFunction).toHaveBeenCalled();
Upvotes: 0