UNIT TESTING

What is Unit Testing?

defined as a type of software testing where individual units/ components of a software are tested.

Why is it Important?

  1. Unit Tests fix bug early in development cycle and save costs.
  2. It helps understand the developers the code base and enable them to make changes quickly.
  3. Good unit tests serve as project documentation
  4. Unit tests help with code re-use. Migrate both your code and your tests to your new project. Tweak the code till the tests run again.

MYTH:

It requires time, and I am always overscheduled
My code is rock solid! I do not need unit tests.

UNIT TEST != INTEGRATION TEST

UNIT TEST is easy to implement

Covers a single piece of code (usually an object or a function) tested the behavior without external resources

UNIT TEST PATTERN

The AAA Phrases

Arrange, Act, Assert

TDD

Test Driven Development

RULES: 

  • You are not allowed to write any production code unless it is to make a failing unit test pass.
  • You are not allowed to write any more of a unit test than is sufficient to fail, and compilation failures are failures.
  • You are not allowed to write any more production code than is sufficient to pass the one failing unit test.

TDD

Testing Framework:

I picked JEST:

  • built-in assertion method
  • multi-environment, it can use in node and browser
  • can watch and run untested code or code changes only
  • built-in coverage

Sometimes We need to mock our data

Mock?

mocking is creating objects that simulate the behavior of real objects.

Mocking framework:

Is there an easy way to test React Component?

Yes:

Advantage

  • Not much boilerplate code
  • No need init setup
  • Enforce to write better test cases
  • No shallow rendering
  • No need forceUpdate

Misc:

describe('Test Fungsi A', () => {
  it('should work perfectly', () => {
    // arrange
    // act
    // assert
  });
});

Example:

Thank you

Unit Testing in React

By ikhsanalatsary

Unit Testing in React

  • 62