DEV Community

Saoud
Saoud

Posted on

3

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)

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!