Tips on Basic Unit Testing

Mark Peñaranda
Mark Penaranda
Published in
2 min readJan 21, 2020

When writing unit tests, I suggest to follow these guidelines to make sure that the test cases have the utmost coverage.

  1. Write the test cases first before the implementation component. — This may sound odd but creating the test cases first will help you identify and understand the requirements on a User-Level Perspective. The most challenging part in writing test cases is identifying which part should be tested. My tip is to wear the user’s hat, and identify what are the items you think you should see and expect as a user.

2. Write the ‘It’ statements first before actually thinking the test code. Just describe and state the ‘It’ statements and just get back to it once you think you’ve identified all the necessary ‘It’ statements

describe('RegistrationForm', () => {  it('should render registration form', () => {
// Do this part later
});});

3. Identify the Test Boundaries , make a list of Positive and Negative test cases, make sure all boundaries are covered.

Positive Test Cases — these are test cases that test valid inputs to verify the software is doing what it’s supposed to do. The main purpose of this is to make sure the system isn’t throwing errors when it’s not supposed to. In general, positive testing ensures the system meets the requirements under positive scenarios.

Negative Test Cases-these are test cases that test the component what it should do when invalid inputs are used. The intent of negative testing is to ensure the system validates against invalid inputs by throwing errors or otherwise not allowing the system to perform in a certain away.

4. Write Test Cases whenever a new bug is found, make sure to write a test function that emulates the bug.

Sample Test File:

For an example lets make a test file for a Registration Form, that has a username field. The username field requires a minimum of 6 characters and maximum of 12 characters

describe('RegistrationForm', () => {  // Render Test Cases
// This is where we make sure that required html and components are rendered
it('should render registration form', () => {
...
});
// Positive Test Cases it('should accept user123 as a valid username because it has 6 characters', () => {
...
});
it('should accept user123456 as a valid username because it is within the 6-12 characters', () => {
...
});
it('should accept user12345678 as a valid username because it has 12 characters', () => {
...
});
// Negative Test Cases it('should show an error message indicating that user1 is not a valid username because it only has 4 characters', () => {
...
});
it('should show an error message indicating that user1234567890 is not a valid username because it has 14 characters', () => {
...
});
});

--

--

Mark Peñaranda
Mark Penaranda

Senior Software Engineer. I write to collect my thoughts and organize my thinking. A journal to keep my ideas and learning.