Writing a Test Without Tools

Write two automated tests without any tools to learn how difficult the practice can be. This will enable you to understand the benefits of these tools in the future.

The function we want to test

Here is the function we want to test:

function isEmail(email) {
  const regex = new RegExp(/^[^@\s]+@[^@\s.]+\.[^@.\s]+$/);
  return regex.test(email);
}

The function validates whether an email address is formatted correctly. The function has no dependencies and doesn’t mutate the email parameter passed into it, which means it is a pure function. Pure functions are simple to test because all their logic is isolated.

We want to write the following two tests:

  • The function should return true when a valid email is passed into it.
  • The function should return false when an invalid email is passed into it.

Writing a happy path test

The first test we’ll write is to verify that the function correctly identifies a valid email address.

The test is available to execute further down the page. Before we run the test, we’ll look at the test code in the following paragraphs.

We’ll write the test in a function. The name of the function will describe the test:

function should_return_true_when_valid_email() {}

In the function implementation, we will create a variable containing the valid email address:

function should_return_true_when_valid_email() {
  const email = "bill@somewhere.com";
}

Next, we will invoke the function we are testing with our test email address:

function should_return_true_when_valid_email() {
  const email = "bill@somewhere.com";
  const result = isEmail(email);
}

We’ll put the result of the function test in a result variable.

Now we can check the return value of the function we are testing is as we expect:

function should_return_true_when_valid_email() {
  const email = "bill@somewhere.com";
  const result = isEmail(email);
  const pass = result === true;
}

We have put whether the test meets our expectations in a pass variable.

Next, we need to fill in the output about whether the test passed:

function should_return_true_when_valid_email() {
  const email = "bill@somewhere.com";
  const result = isEmail(email);
  const pass = result === true;
  console.log(
    pass ? "✅ PASS:" : "❌ FAIL:",
    "The function should return true when a valid email is passed into it"
  );
}

Once we have output the result of the test to the console, we’ll learn whether the test has passed or not:

function should_return_true_when_valid_email() {
  const email = "bill@somewhere.com";
  const result = isEmail(email);
  const pass = result === true;
  console.log(
    pass ? "✅ PASS:" : "❌ FAIL:",
    "The function should return true when a valid email is passed into it"
  );
  return pass;
}

The isEmail function and the test are in the code widget below. Run the widget to see whether the test passes.

Get hands-on with 1200+ tech skills courses.