Unit testing. Just hearing those words might send a shiver down your spine.
Maybe it reminds you of a time when you confidently wrote tests, only to watch them fail spectacularly and question your entire existence.
Or maybe you just pretend unit testing doesn’t exist and hope your code never breaks (spoiler: it will).
Well, its not as inmpossible as it might feel..
Lets look at some simple setups for testing with React and Angular.
🛠️ Why Unit Testing Matters (Yes, It Really Does!)
- Catches bugs early – Saves you from future nightmares.
- Improves refactoring confidence – Make changes without fear.
- Encourages better code – Forces you to write modular, testable code.
- Makes onboarding easier – New devs can read tests to understand the codebase.
⚡ Setting Up Testing in Angular
1️⃣ The Testing Stack
Angular comes with Jasmine (for writing tests) and Karma (for running them). It’s like Batman and Robin but for unit tests.
To get started:
|
|
Boom! You now have a fully functional testing environment.
2️⃣ Writing Your First Test (It’s Not That Scary!)
A simple Angular component test looks like this:
|
|
Not too bad, right? You’re just setting up the component, creating an instance, and making sure it actually exists.
3️⃣ Mocking Dependencies with TestBed
Real services in tests? Nope. We mock those bad boys.
|
|
And boom! No more flaky API calls in tests.
⚡ Setting Up Testing in React
1️⃣ The Testing Stack
For React, the holy trinity of testing tools is:
- Jest – The test runner.
- React Testing Library – A better way to test components.
- Mock Service Worker (MSW) – Mocks API calls.
To set up:
|
|
2️⃣ Writing Your First Test (Piece of Cake!)
|
|
That’s it! No complex setup, no unnecessary mocks, just testing the output.
3️⃣ Mocking API Calls in React
For API calls, Jest and MSW are your friends.
Mocking Fetch with Jest
|
|
Or, even better, use Mock Service Worker (MSW):
|
|
🏆 Best Practices for Both Angular and React
✅ Write small, isolated tests – Each test should focus on one thing.
✅ Mock dependencies – Keep tests fast and reliable.
✅ Use meaningful test names – it('should render a button')
is better than it('test1')
.
✅ Avoid testing implementation details – Test behavior, not internals.
✅ Run tests automatically – Set up CI/CD to catch bugs before deployment.
🔑 Key Ideas
Concept | Details |
---|---|
Unit Testing Importance | Catches bugs early, improves confidence |
Angular Testing Stack | Jasmine & Karma |
React Testing Stack | Jest & React Testing Library |
Mocking in Angular | Use TestBed.configureTestingModule |
Mocking in React | Use Jest or MSW |
Best Practices | Write small tests, mock dependencies, meaningful test names |