DEV Community

Saoud
Saoud

Posted on

Test Driven Development and Looping with map

Terminology


  • Test-Driven Development: A workflow used by developers across coding languages. In TDD, we write tests that describe our application's behavior. Then we write the minimal amount of code we need to get the test passing. The goal is to break larger problems into more manageable steps and also to make sure our code is working correctly.
  • TestsSpecifications or Specs: Examples of small, isolated behaviors a program should demonstrate, including input and output examples. Spec and test are interchangeable terms.

Example


Here's an example of a pseudocoded test:

Describe: add()
Test: "It adds two numbers together and returns the sum"
Code: const sum = add(2,3);
Expect(sum).toEqual(5);
Enter fullscreen mode Exit fullscreen mode

Here's what the same test would look like using Jest, the testing framework we'll be using in Intermediate JavaScript and beyond:

describe('add()', () => {
  test('should correctly add two numbers together', () => {
    const sum = add(2,3);
    expect(sum).toEqual(5);
  });
});
Enter fullscreen mode Exit fullscreen mode

Terminology


  • Array.prototype.map(): We can use this to loop over an array, creating a new array with transformed elements.

Example


The following loops through each item in the numbers array, multiplies it by 2, and places it in a new array called doubleNumbers:

const numbers = [1,2,3,4,5];
const doubledNumbers = numbers.map(function(number) {
  return number * 2;
});
Enter fullscreen mode Exit fullscreen mode

Don't forget that you need to have a return statement - otherwise, Array.prototype.map() will return undefined.

Top comments (0)