Points to remember before writing Test Cases

Single Responsibility Principle (SRP)

  1. Clear and focused tests

By following SRP, each unit test focuses on testing only one specific behavior or functionality of the code. This makes the test case clearer and easier to understand.

  1. Easier maintenance

When tests have a single responsibility, any changes or updates to the code under test will likely require only one corresponding update to the test case. This simplifies maintenance and reduces the risk of introducing errors.

  1. Modularity and reusability

Independent and well-focused tests are more likely to be reusable in other parts of the codebase, promoting modularity and reducing code duplication.

One Assert Per Unit Test

  1. Clarity of test outcome

Having a single assert per test ensures that the test’s outcome is straightforward and easy to interpret. The test passes if the assert passes and fails if the assert fails. This makes it clear what specific aspect of the code is being tested

  1. Isolation of failures

When a test contains multiple asserts and one of them fails, it might be challenging to pinpoint the exact cause of the failure. By having only one assert per test, it becomes easier to identify the specific condition that caused the failure

  1. Independent testing

 Tests with one assert are more independent, meaning the success or failure of one assert doesn’t affect the execution of other asserts in the same test. This ensures that all relevant scenarios are tested regardless of the outcome of individual parts

Wrong way of doing

Correct way of doing

import { assert } from '.';
describe('AwesomeDate', () => {
  it('handles date boundaries', () => {
    let date: AwesomeDate;
    date = new AwesomeDate('1/1/2015');
    assert.equal('1/31/2015', date.addDays(30));
    date = new AwesomeDate('2/1/2016');
    assert.equal('2/29/2016', date.addDays(28));
  });
});
import { assert } from '.';
describe('AwesomeDate', () => {
  it('handles 30-day months', () => {
    const date = new AwesomeDate('1/1/2015');
    assert.equal('1/31/2015', date.addDays(30));
  });
  it('handles leap year', () => {
    const date = new AwesomeDate('2/1/2016');
    assert.equal('2/29/2016', date.addDays(28));
  });
});