Intro
Let's understand the stubs and their occurrence in software testing. What they are, when they can be used, and how to use them?
Prelude
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.
Loading
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?
Next problem is on JavaScript side. What will happen when select component will try to access initially of the required properites but they will be undefined? That's right... Big bum đ„.
That's exactly why you need stubs!
Summary
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
10 minutes
Software testing
2 m
Grouping the tests
1 minute
The usage of describe and it
2 m
The best practices for naming tests
2 m
Navigating the different types of software tests
3 m
- 2. Mastering unit testing
38 minutes
Project and tests setup
3 m
Unit tests review
4 m
React component testing
5 m
Snapshot testing in React
4 m
Understanding stubs in testing
3 m
Understanding mocks in testing
5 m
Creating testing fixtures
4 m
Using spies in React and Typescript
3 m
Mocking environment variables
3 m
Using dependency injection pattern to improve fixtures
4 m
- 3. Mastering integration testing
12 minutes
Understanding the integration tests
4 m
Using MSW library to remove implementation details from tests
4 m
Creating fixture for MSW to reduce boilerplate and setup
4 m
- 4. Mastering e2e tests
8 minutes
Comments
Add your honest opinion about this article and help us improve the content.