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.
it('allows to pass custom placeholder', () => {
const propsStub: SelectProps = {
options: [],
onChange: () => {}
};
// You'll test only placeholder but you need
// to pass options and onChange to make TypeScript calm.
render(
<Select {...propsStub} placeholder="placeholder" />
);
screen.getByText(/placeholder/);
});
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!
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
Types of tests
3 m
- 2. Mastering unit testing
31 minutes