MG Software.
HomeAboutServicesPortfolioBlogCalculator
Contact Us
MG Software
MG Software
MG Software.

MG Software builds custom software, websites and AI solutions that help businesses grow.

© 2026 MG Software B.V. All rights reserved.

NavigationServicesPortfolioAbout UsContactBlogCalculator
ServicesCustom developmentSoftware integrationsSoftware redevelopmentApp developmentSEO & discoverability
Knowledge BaseKnowledge BaseComparisonsExamplesAlternativesTemplatesToolsSolutionsAPI integrations
LocationsHaarlemAmsterdamThe HagueEindhovenBredaAmersfoortAll locations
IndustriesLegalEnergyHealthcareE-commerceLogisticsAll industries
MG Software.
HomeAboutServicesPortfolioBlogCalculator
Contact Us
MG Software
MG Software
MG Software.

MG Software builds custom software, websites and AI solutions that help businesses grow.

© 2026 MG Software B.V. All rights reserved.

NavigationServicesPortfolioAbout UsContactBlogCalculator
ServicesCustom developmentSoftware integrationsSoftware redevelopmentApp developmentSEO & discoverability
Knowledge BaseKnowledge BaseComparisonsExamplesAlternativesTemplatesToolsSolutionsAPI integrations
LocationsHaarlemAmsterdamThe HagueEindhovenBredaAmersfoortAll locations
IndustriesLegalEnergyHealthcareE-commerceLogisticsAll industries
MG Software.
HomeAboutServicesPortfolioBlogCalculator
Contact Us
MG Software
MG Software
MG Software.

MG Software builds custom software, websites and AI solutions that help businesses grow.

© 2026 MG Software B.V. All rights reserved.

NavigationServicesPortfolioAbout UsContactBlogCalculator
ServicesCustom developmentSoftware integrationsSoftware redevelopmentApp developmentSEO & discoverability
Knowledge BaseKnowledge BaseComparisonsExamplesAlternativesTemplatesToolsSolutionsAPI integrations
LocationsHaarlemAmsterdamThe HagueEindhovenBredaAmersfoortAll locations
IndustriesLegalEnergyHealthcareE-commerceLogisticsAll industries
MG Software.
HomeAboutServicesPortfolioBlogCalculator
Contact Us
  1. Home
  2. /Knowledge Base
  3. /What is Unit Testing? - Explanation & Meaning

What is Unit Testing? - Explanation & Meaning

Unit testing tests individual functions and components in isolation using Jest, Vitest, or pytest, and forms the first line of defense against software bugs.

Unit testing is the automated practice of verifying the smallest units of source code, such as individual functions, methods, or classes, in complete isolation from the rest of the system. The primary goal is to confirm that each unit behaves correctly according to its specification, regardless of database state, network availability, or other external factors. By validating building blocks independently, you create a reliable foundation on which integration and end-to-end tests build.

What is Unit Testing? - Explanation & Meaning

What is Unit Testing?

Unit testing is the automated practice of verifying the smallest units of source code, such as individual functions, methods, or classes, in complete isolation from the rest of the system. The primary goal is to confirm that each unit behaves correctly according to its specification, regardless of database state, network availability, or other external factors. By validating building blocks independently, you create a reliable foundation on which integration and end-to-end tests build.

How does Unit Testing work technically?

Unit tests form the broad base of the testing pyramid, a model described by Mike Cohn in "Succeeding with Agile". Compared with integration and end-to-end tests, they are the cheapest to write, fastest to run, and easiest to maintain. The FIRST principles state that unit tests must be Fast, Isolated, Repeatable, Self-validating, and Timely. Fast means a full suite finishes in seconds so developers can run it on every save. Isolated ensures no shared state or external services are required. Repeatable guarantees identical results regardless of when or where the test runs. Self-validating means every test passes or fails automatically without manual inspection. Timely means tests are written when the code is created, or even before it in test-driven development. Leading frameworks include Jest and Vitest for JavaScript and TypeScript, pytest for Python, JUnit 5 for Java, and xUnit for .NET. Vitest provides native ESM support, parallel execution via worker threads, and a Jest-compatible API that simplifies migration. Pytest relies on fixtures as a dependency injection mechanism and offers parametrize decorators for data-driven tests. Mocking is central to unit testing. Libraries such as vi.mock() in Vitest or unittest.mock in Python replace external dependencies with controlled doubles, ensuring you test only the logic of the unit itself. Spies record how functions are invoked without altering behavior, which is useful for verifying interactions. Code coverage tools like Istanbul (via c8 or nyc) report line, branch, function, and statement coverage. An 80% target is a solid guideline, but assertion quality matters more than the percentage. Snapshot testing compares current output against stored references and is particularly effective for UI components. Property-based testing, supported by fast-check in JavaScript or Hypothesis in Python, generates hundreds of random inputs to expose unexpected edge cases. Mutation testing, supported by tools like Stryker for JavaScript or mutmut for Python, evaluates test suite quality by introducing small code modifications and verifying that existing tests detect them. Contract testing with Pact validates that services conform to agreed-upon API schemas, bridging the gap between unit and integration testing.

How does MG Software apply Unit Testing in practice?

At MG Software, unit testing is woven into our daily development workflow. We write tests for every piece of business-critical logic before it reaches production. For our TypeScript and React projects, we rely on Vitest because of its fast startup time and native ESM compatibility. Python services are tested with pytest, where fixtures keep test data consistent and reproducible. Our CI/CD pipeline in GitHub Actions runs the full test suite on every pull request and blocks merges whenever tests fail or coverage drops below the agreed threshold. Code review serves as an additional safeguard: reviewers evaluate not just the production code but also the quality and completeness of accompanying tests. By combining unit tests with integration tests and Playwright end-to-end tests, we ensure reliability at every layer of the application stack.

Why does Unit Testing matter?

Fast, isolated unit tests give developers confidence within seconds on every code change. That makes refactoring safe and test-driven development practically viable. Because unit tests run first in the testing pyramid, they catch regressions before slower integration or end-to-end suites even start. This dramatically shortens the feedback loop: a bug found in five seconds costs a fraction of the time compared to one discovered after a full deployment cycle. Teams without a solid unit layer find that releases take longer, developers become reluctant to modify existing code, and subtle defects accumulate in production. Investing in unit tests pays for itself within weeks through higher development velocity, fewer production incidents, and the confidence to refactor without fear of silent breakage.

Common mistakes with Unit Testing

A common mistake is testing implementation details rather than behavior. When tests verify which internal methods are called instead of what the function returns, they break on every refactoring even though no actual bug exists. A second pitfall is excessive mocking: if a test contains more mocks than real logic, you are essentially testing the mocks themselves. Keep mocks limited to genuine external dependencies such as databases and API calls. Another trap is blindly chasing 100% coverage without examining assertion quality. A test that executes code but validates nothing inflates the coverage number without adding value. Finally, teams often neglect test maintenance: outdated tests that fail get ignored or disabled, eroding trust in the entire suite and defeating the purpose of automated testing.

What are some examples of Unit Testing?

  • A unit test that verifies a price calculation function returns correct results for regular prices, percentage discounts, tiered discounts, VAT calculations, and edge cases such as zero values, negative amounts, and extremely large inputs that could cause overflow.
  • An isolated test of an authentication service using vi.mock() to simulate the database layer. The test confirms that valid credentials produce a JWT token, that invalid credentials return a specific error, and that passwords are never stored in plaintext.
  • A CI/CD pipeline in GitHub Actions running 500 unit tests in under 30 seconds on every commit, catching regressions immediately and blocking the merge to main until all tests pass green.
  • A parametrized test in pytest that validates a date-parsing function with dozens of input combinations: valid dates, leap years, invalid months, negative years, and empty strings, all within a single test function using the @pytest.mark.parametrize decorator.
  • Snapshot tests in Vitest comparing the rendered output of React components against stored references. When a developer changes styling or structure, the snapshot fails and must be consciously approved via the --update flag before the test passes again.

Related terms

test driven developmentclean coderefactoringcontinuous deploymentcode review

Further reading

Knowledge BaseWhat are Design Patterns? - Explanation & MeaningWhat is Clean Code? - Explanation & MeaningTesting Frameworks Our Team Actually Relies OnSoftware Development in Amsterdam

Related articles

What Is an API? How Application Programming Interfaces Power Modern Software

APIs enable software applications to communicate through standardized protocols and endpoints, powering everything from payment processing and CRM integrations to real-time data exchange between microservices.

What Is SaaS? Software as a Service Explained for Business Leaders and Teams

SaaS (Software as a Service) delivers applications through the cloud on a subscription basis. No installations, automatic updates, elastic scalability, and secure access from any device make it the dominant software delivery model for modern organizations.

What Is Cloud Computing? Service Models, Architecture and Business Benefits Explained

Cloud computing replaces costly local servers with flexible, on-demand IT infrastructure delivered through IaaS, PaaS, and SaaS from providers like AWS, Azure, and Google Cloud. Learn how it works and why it matters for your business.

Software Development in Amsterdam

Amsterdam's thriving tech scene demands software that keeps pace. MG Software builds scalable web applications, SaaS platforms, and API integrations for the capital's most ambitious businesses.

From our blog

Why Testing Is Essential for Your Software

Sidney · 6 min read

Frequently asked questions

A test coverage target of 70-80% is a solid guideline for most projects. The percentage alone tells you little, though: it is far more important to cover critical paths, complex business logic, and edge cases thoroughly than to chase 100% blindly. Trivial getters, pure configuration files, and generated code do not necessarily need tests. Focus on assertions that genuinely validate behavior rather than lines that happen to execute without meaningful verification. Tools like Istanbul report branch coverage alongside line coverage, giving a more accurate picture.
A mock is a simulated object that defines expected behavior and verifies methods are called correctly with the right arguments. A stub returns predefined values without checking call behavior. A spy wraps the real implementation and records calls, arguments, and return values without altering the original behavior. In frameworks like Vitest and Jest, these concepts overlap: vi.fn() and jest.fn() combine mock and spy functionality in a single API, making the distinction less rigid in practice.
For JavaScript and TypeScript, Vitest is the modern standard thanks to native ESM support, parallel execution, and a Jest-compatible API. Jest remains a reliable choice for existing projects with large test suites. For Python, pytest dominates because of its clear syntax, powerful fixture system, and extensive plugin ecosystem. JUnit 5 is standard for Java, xUnit for .NET. Choose based on your language ecosystem, team experience, and how well the framework integrates with your build tooling and CI pipeline.
Use React Testing Library combined with Vitest or Jest. Test components from the user perspective: query elements by role, label, or text rather than internal class names or data attributes. Verify that the correct content renders, that events are handled properly, and that state changes produce the expected UI updates. Avoid testing implementation details like internal state variables. Prefer userEvent over fireEvent for more realistic interaction simulation that better matches actual browser behavior.
Unit tests verify a single function or class in complete isolation, with all dependencies mocked. Integration tests verify the collaboration between multiple components, for example a service that actually calls a database. Unit tests are faster and pinpoint bugs precisely, but they miss problems in the interaction between parts. A healthy test strategy combines both: many fast unit tests for logic and a smaller number of integration tests for critical connections and data flow across boundaries.
Do not try to retroactively test the entire codebase at once. Start with code you plan to modify soon or areas where bugs have occurred. Write a "characterization test" that captures the current behavior before you refactor. Add a regression test with every bug fix that reproduces the specific defect. This way, coverage grows organically in the places where it matters most, without investing months in a catch-up effort that delays feature work.
Slow unit tests usually indicate insufficient isolation: tests that hit real databases, networks, or the file system. Mock external dependencies consistently. Avoid global setup that runs before every test and leverage parallel execution, which Vitest enables by default. Keep tests small and focused on a single scenario. If your suite grows large regardless, split into shards that run concurrently in CI. Monitor execution time regularly so slowdowns become visible immediately rather than creeping in over weeks.

We work with this daily

The same expertise you're reading about, we put to work for clients.

Discover what we can do

Related articles

What Is an API? How Application Programming Interfaces Power Modern Software

APIs enable software applications to communicate through standardized protocols and endpoints, powering everything from payment processing and CRM integrations to real-time data exchange between microservices.

What Is SaaS? Software as a Service Explained for Business Leaders and Teams

SaaS (Software as a Service) delivers applications through the cloud on a subscription basis. No installations, automatic updates, elastic scalability, and secure access from any device make it the dominant software delivery model for modern organizations.

What Is Cloud Computing? Service Models, Architecture and Business Benefits Explained

Cloud computing replaces costly local servers with flexible, on-demand IT infrastructure delivered through IaaS, PaaS, and SaaS from providers like AWS, Azure, and Google Cloud. Learn how it works and why it matters for your business.

Software Development in Amsterdam

Amsterdam's thriving tech scene demands software that keeps pace. MG Software builds scalable web applications, SaaS platforms, and API integrations for the capital's most ambitious businesses.

From our blog

Why Testing Is Essential for Your Software

Sidney · 6 min read

MG Software
MG Software
MG Software.

MG Software builds custom software, websites and AI solutions that help businesses grow.

© 2026 MG Software B.V. All rights reserved.

NavigationServicesPortfolioAbout UsContactBlogCalculator
ServicesCustom developmentSoftware integrationsSoftware redevelopmentApp developmentSEO & discoverability
Knowledge BaseKnowledge BaseComparisonsExamplesAlternativesTemplatesToolsSolutionsAPI integrations
LocationsHaarlemAmsterdamThe HagueEindhovenBredaAmersfoortAll locations
IndustriesLegalEnergyHealthcareE-commerceLogisticsAll industries