Article thumbnail

⭐ Understanding stubs in testing

3m
frontend
testing
quality

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.

I create content regularly!

I hope you found my post interesting. If so, maybe you'll take a peek at my LinkedIn, where I publish posts daily.

Comments

Add your honest opinion about this article and help us improve the content.

created: 10-04-2023
updated: 10-05-2023