DEV Community

Cover image for The Secret of Producing Less Bug🐞 In Your ReactJS Projects!
ghack.dev
ghack.dev

Posted on

The Secret of Producing Less Bug🐞 In Your ReactJS Projects!

I will start with a very simple question.

Why are we producing a bugs?

🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞🐞
Because we are human, we're making a lot of mistakes while living on this earth. So, what can we do with it? πŸ€”

Anyone who has never made a mistake has never tried anything new. - Albert Einstein

It's okay to make mistakes. But what i mean by making a mistake here is when you are on a Sunday vacation with your family or a date with your beloved girlfriend or boyfriend until your boss calling you and say that some functionalities in the app that you've built doesn't work or some clients are complaining because there are bugs in the app. 😩

Those kind of conditions will definitely throw away our joyful weekend to the garbage. So, how can we avoid those kind of conditions? One of the best answer of this question is Unit Test.

No time for it! ⏱

Yeah, if we're working on a startup that everything should be delivered ASAP, maybe we can easily say that we don't have time to write unit tests. Especially if we're working as a front-end to build an UI, we'll just let the QA to test it manually.

STOP! ⛔️

Believe me, if you are a React developers and you decide to start to write a tests today. Your life we'll be much easier and happier than before.

It's easy and fast... πŸš€

In this article i'll show you that writing tests in React project is a very easy and fast job. Just do some practice, let your muscle memory get used to it, and you'll find it easier to do this job.

I'm not going to show you about how to write tests in React only, but I will also show you how to do TDD in React correctly and how to write a good tests in your React project. So you can enjoy the process of writing the tests, and have a peaceful weekend. πŸ™†πŸ»β€β™‚οΈ

TDD (Test Driven Development)

TDD is about creating a code that we trust and the code that we can proud of. It's very simple, just remember these three steps :

  1. RED. Make it fail.
  2. GREEN. Make it pass.
  3. YELLOW. Refractor.

No cheap talks, let's code! πŸ‘¨β€πŸ’»

Preparation

We'll create a fresh react project and then we'll start using TDD to build a very simple Counter App.

Just install React by using this command :

npx create-react-app react-tdd-sample

Install Enzyme library :

npm i -D enzyme

And also these libraries :

npm i -D react-test-renderer enzyme-adapter-react-16

Create new file named setupTests.js inside src folder or if it exists, just modify the code to be like this :

import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

configure({ adapter: new Adapter() });

Okay I think that we are ready. Let's start writing our component.

1. Write a failing test.

Write a test to prove that the next small piece of functionality is missing or wrong.

Okay first, we'll write a simple failing test. Just create new file called Counter.spec.js inside src/components folder.

import React from 'react';
import { shallow } from 'enzyme';
import Counter from './Counter';

describe('Counter', () => {
  let wrapper;

  it('should render a number', () => {
    wrapper = shallow(
      <Counter />
    );
    expect(wrapper.find('.Counter__container__number').length).toEqual(1);
  });
});

And then, just create a very basic React Component. Create new file named Counter.js in the same folder and write down this code.

import React from 'react';

const Counter = () => {
  return (
    <div className="Counter__container">
      This is Counter component.
    </div>
  );
};

export default Counter;

2. Run the test.

Just run a test by using this command :

npm test

The test should be fail this time. Just make it feel like it's a bug. The reason behind this step is that we need to prove that the test is good. We test the test, it will brings us trust.

3. Refractor the component, as simple as possible to pass the test

To past our first test, we just need to refractor our component to be like this.

import React from 'react';

const Counter = () => {
  return (
    <div className="Counter__container">
      <p
        className="Counter__container__number"
      >
      </p>
    </div>
  );
};

export default Counter;

4. Run the test.

This time, the first test should be passed.

5. Incrementally refractor the test or the Component code.

We know that we only create a <p> tag and there is nothing inside, it's not actually render a number. Let's refractor the codes.

Refractor our test to be like this.

import React from 'react';
import { shallow } from 'enzyme';
import Counter from './Counter';

describe('Counter', () => {
  let wrapper;

  it('should render a number', () => {
    wrapper = shallow(
      <Counter />
    );
    expect(wrapper.find('.Counter__container__number').length).toEqual(1);
    expect(wrapper.find('.Counter__container__number').text()).toEqual('0');
  });
});

And refractor our Counter Component to be like this.

import React from 'react';

const Counter = () => {
  return (
    <div className="Counter__container">
      <p
        className="Counter__container__number"
      >
        0
      </p>
    </div>
  );
};

export default Counter;

6. Run the code.

After do a small refractor to your test code and Component code. Run the code and it should passed.

That's it!

Those steps, from first step to the sixth step. In those steps, we've seen that we have two loops. The inner loop is start from step five to six. We can repeat step five to six until we like the code.

Okay, just look at this picture :
tdd

In the picture above, the design happens two times. On the first step of the outer loop and on the first step of the inner loop.

In the outer loop, we're creating a code that we trust. In the inner loop, we're creating a code that we like, the code that we can proud of. You know, sometimes we just write an ugly code that works but we hate it.

Conclusions...

TDD is about creating a code that we trust and the code that we like.

Some questions...

Why do we write test before we write the code?
Otherwise you’ll have no time to write them.

Why do we make the test fail first?

To test the test.

Why do we solve it as simply as possible?

Simpler solutions are easier to maintain.

Why refractor?

To constantly improve the design of the code. Remove duplication and maintainability.

Why work incrementally?

Something working is better than nothing. Small units of work are easier for people better life!

The benefits?

Less bugs!
Better designed interfaces!
Happier life! For customers and coders!

Finish the project!

Okay right now you can practice it yourself. Continue the Counter App project by following the steps. You can add more functionalities like passing an initial value to the counter and create two buttons to increase and decrease the number.

This article is based on this video :
https://www.youtube.com/watch?v=oneGCBiPK_Q

Top comments (0)