Skip to content

Instantly share code, notes, and snippets.

@jackie1santana
Created June 24, 2025 16:49
Show Gist options
  • Save jackie1santana/62e8b86cf0d775bbae1e14286140acce to your computer and use it in GitHub Desktop.
Save jackie1santana/62e8b86cf0d775bbae1e14286140acce to your computer and use it in GitHub Desktop.
✅ What This Example is Doing
1. It's mocking window.Bootstrapper._trackAnalytics:
ts
Copy
Edit
window.Bootstrapper = {
// @ts-ignore eslint
_trackAnalytics: jest.fn()
};
This fakes the real analytics function so Jest doesn’t explode.
2. Then it tests if your function actually called it:
ts
Copy
Edit
expect(window.Bootstrapper._trackAnalytics).toHaveBeenCalled();
Boom. ✅ Tracked and tested.
⚙️ SET UP TRACKANALYTICS TESTING — FOR YOUR CODE
Let’s say inside your component you got something like this:
ts
Copy
Edit
goToIntroPage(): void {
window.Bootstrapper._trackAnalytics({ event: 'GO_TO_INTRO' });
this.router.navigate(['/intro']);
}
🧪 TEST: goToIntroPage() calls trackAnalytics
Here’s your Jest test you can drop in:
ts
Copy
Edit
describe('goToIntroPage', () => {
beforeEach(() => {
// ✅ mock analytics before every test
window.Bootstrapper = {
_trackAnalytics: jest.fn()
};
});
it('should call trackAnalytics when navigating to intro page', () => {
component.goToIntroPage();
expect(window.Bootstrapper._trackAnalytics).toHaveBeenCalledWith({
event: 'GO_TO_INTRO'
});
// Optional: if you want to test navigation too
expect(window.location.href).toContain('/intro'); // or use router spy
});
});
🧪 TEST: ngOnInit() calls trackAnalytics (if used there too)
ts
Copy
Edit
describe('ngOnInit', () => {
beforeEach(() => {
window.Bootstrapper = {
_trackAnalytics: jest.fn()
};
});
it('should track analytics on init', () => {
component.ngOnInit();
expect(window.Bootstrapper._trackAnalytics).toHaveBeenCalledWith({
event: 'PAGE_LOAD'
});
});
});
🛠️ If You’re Using trackAnalytics() Imported Directly
If your method doesn’t go through window.Bootstrapper, but instead directly calls:
ts
Copy
Edit
import { trackAnalytics } from '@app/services/common/track-analytics/analytics';
trackAnalytics({ event: 'GO_TO_INTRO' });
Then replace the mock like this:
ts
Copy
Edit
jest.mock('@app/services/common/track-analytics/analytics', () => ({
trackAnalytics: jest.fn()
}));
import { trackAnalytics } from '@app/services/common/track-analytics/analytics';
Then just test it like:
ts
Copy
Edit
expect(trackAnalytics).toHaveBeenCalledWith({ event: 'GO_TO_INTRO' });
💡 Philosopher’s Final Take (Ryan Holiday Style):
“Don't be flashy with your code — be effective. When something breaks, it’s not a failure. It’s a signal. Track it. Test it. Own it.”
Now go finish that test suite strong, bro 💪
Want me to help write a real test from your actual method? Paste the method and I’ll whip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment