Why unit tests?

Before we look at Jest, we need to answer a question: Why unit tests? Writing unit tests gives you a number of benefits:

  • Automate your tests so you don’t have to test them manually every time.
  • Change check, when the code refactoring, can be found in time, and make the corresponding adjustment.
  • Enumerating test cases will help you understand all the boundary cases.
  • The generated test report can even be used as documentation if your test description is detailed enough.

In short, unit testing will make your life better.

Use Jest for unit testing

Tests are usually written based on one of the frameworks, and I chose Jest, not only because I’m a React developer (both React and Jest are from Facebook), but also because it’s really easy to use. Let’s start writing tests! First, install Jest:

npm install --save-dev jest
Copy the code

Then, write a file to test, using the Stack class as an example:

function Stack() {
  // Private variable items, used to record arrays, objects cannot be manipulated directly
  var items = [];
  // Class method push, which adds items to the end of the array, objects can be called directly
  this.push = function (element) {
    items.push(element);
  };
  // Remove and return the item at the end of the array
  this.pop = function () {
    return items.pop();
  };
}
Copy the code

Next, write a test file stack.test.js:

/ / import Stack
var Stack = require('./Stack');

test('Stack'.function () {
  // Instantiate a stack object
  var stack = new Stack();

  stack.push(4);
  // Expect the last item in the stack to be 4
  expect(stack.pop()).toBe(4);
});
Copy the code

Then, add to package.json:

"scripts": {
  "test": "jest"
}
Copy the code

Finally, open the command line and run:

npm test
Copy the code

The result generates a test report on the command line:

PASS  Stack.test.js

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.386s
Ran all test suites.
Copy the code

Introduction of assertions

In the above test code there is an expect().tobe () to determine whether the result is expected, called an assertion. What is an assertion? In programming, an assertion is an assertion of first-order logic (such as a true or false result) placed within a program to identify and verify an expected result. In addition to expect().tobe (), other common assertions include:

  • Expect ().toequal () : checks whether the result is equivalent to the expected result.
  • Expect ().tobefalsy () : determine whether the result is false.
  • Expect ().tobetruthy () : determine whether the result is true.

At this point, Jest’s introductory usage has been demonstrated. For more information, see its official documentation at facebook.github. IO/Jest /