Let's understand the stubs and their occurrence in software testing. What they are, when they can be used, and how to use them?
A stub is a simple, static object that is used to provide predictable responses to method calls. It is typically used to replace a dependency that is not directly related to the functionality being tested, but is required for the test to run.
Wait, what? Yea, we need an example to understand this.
Examples of stubs
Imagine the situation when you have already Select component implemented. It takes several properties and some of them are required. You want to test placeholder displaying feature and be able to detect bugs without any in-depth checks.
Congrats! You've created your first stub, but why you needed that?
The TypeScript will scream that there are missing properties: options array and onChange function. You can cast it to as any, but it's wrong solution. Why you need TypeScript if you want to disable type-checking?
That's exactly why you need stubs!
Now you know what stubs are for. It's not a concept only related with React components or React testing. This approach is universal and completely independent from the technology you are working in - just like SOLID principles.
You can stub classes, objects and others just to be able to test one dedicated part of something bigger.
If you enjoyed it, be sure to visit us on Linkedin where we regularly upload content from programming.
- 1. Basics
Grouping the tests
The usage of describe and it
The best practices for naming tests
Navigating the different types of software tests
- 2. Mastering unit testing
Project and tests setup
Unit tests review
React component testing
Snapshot testing in React
Understanding stubs in testing
Understanding mocks in testing
Creating testing fixtures
Using spies in React and Typescript
Mocking environment variables
Using dependency injection pattern to improve fixtures
- 3. Mastering integration testing
Understanding the integration tests
Using MSW library to remove implementation details from tests
Creating fixture for MSW to reduce boilerplate and setup
- 4. Mastering e2e tests