Translation by Marcin Wanago: Crazy techie

This article is the first in a series of JavaScript testing tutorials

    1. JavaScript Testing Tutorial – Part 1: Unit Testing with Jest
    1. JavaScript Test Tutorial – Part 2: Introduce the Enzyme and test the React component
    1. JavaScript Testing Tutorial — Part 3: Testing props, mount functions, and Snapshot testing
    1. JavaScript Test Tutorial — Part 4: Simulating API calls and simulating React component interactions

There are different kinds of tests, and I’ll explain some of them first. First, I’ll cover the basics of unit testing, which is testing each part of your application and checking that it’s fit for use. To do this, we will use Jest, a testing framework developed by Facebook. It is ready and has the functionality required for testing.

Types of tests

Tests are code that checks your code. Testing gives you more confidence in your program. They also prevent you from fixing one bug while creating another. You can test every aspect of a program, from individual functions and their return values to complex programs running in a browser. Since this is the first article of the course, I will briefly compare some popular test types.

Unit testing

Unit tests cover blocks of code to ensure that they are problem-free at run time. The units being tested can be functions, modules, classes, and so on. Unit tests should be isolated and independent of each other. Checking the results with unit tests for a given input can help you ensure that every part of your program works as expected by catching problems early and avoiding degradation.

Integration testing

Even if you pass all your unit tests, it only means that everything works. Still, the program may fail. Integration testing covers a cross-module process where modules are combined and tested as they work together. Thanks to him, you have a way to make sure your code works as a whole.

End-to-end Testing (E2E)

In contrast to other types of testing, end-to-end testing is always run in a browser (or browser-like) environment. It might be a real browser that is open and running tests in it. It can also be a headless browser environment, that is, a browser that runs without a user interface. The E2E test focused on simulating real users in the program we were running. They simulate behaviors like scrolling, clicking, and typing, and check that our program works from the point of view of the real user.

Unit testing with Jest

Jest is a testing framework developed by Facebook. One of its goals is to provide a “zero configuration” experience with off-the-shelf tools. It’s been around for a while, and it’s fast and reliable.

npm install --save-dev jest
Copy the code

Don’t forget to add it to your NPM script.

package.json
"scripts": {
  "test": "jest"
}
Copy the code

For simplicity, I’ll use Jest here with a simple pure Node.js module (excluding Webpack). Later we’ll learn how to use Jest in React

First, let’s create some simple functions that you can test.

divide.js
function divide(a, b) {
  return a / b;
}
module.exports = divide;
Copy the code

Jest uses regular expressions to determine which file to test. ** By default,.js and.jsx files will be executed if they are in the Tests directory or have the suffix test or.spec. You can specify this in the project’s package.json file using the testRegex property.

package.json
"jest": {
  "testRegex": "(/__tests__/.*|(\\.|/)(test|spec))\\.jsx?$"
}
Copy the code

Finally, let’s create the test file. To follow the default naming configuration, we named it separate.test.js.

divide.test.js
const divide = require('./divide');
 
test('dividing 6 by 3 equals 2', () => {
  expect(divide(6.3)).toBe(2);
});
Copy the code

Run the test with the NPM run test command:

PASS./divide. Test. Js ramp 6 by 3 equals 2 (5ms)Copy the code

The test function is used to run tests. It takes three parameters: the name of the test, the function that contains the expected value, and the timeout in milliseconds. The timeout defaults to 5 seconds and specifies how long to wait before aborting the test if it takes too long.

The Expect function is used to test values. As an argument, it takes the value you’re testing: in our case, it’s the return from Divide. You can test this value in some way by calling a set of Matcher functions (toBe used in the example). For complete information, visit the Jest documentation.

Grouping test

There will usually be more than one test per file. With Jest, you can group them using the describe function. It creates a block that can merge multiple tests. To better display it, let’s run some tests on the global Math object.

describe('in the math global object', () => {
 
  describe('the random function', () => {
    it('should return a number', () => {
      expect(typeof Math.random()).toEqual('number');
    })
    it('should return a number between 0 and 1', () = > {const randomNumber = Math.random();
      expect(randomNumber).toBeGreaterThanOrEqual(0);
      expect(randomNumber).toBeLessThan(1); })}); describe('the round function', () => {
    it('should return a rounded value of 4.5 being 5', () => {
      expect(Math.round(4.5)).toBe(5); })}); })Copy the code

You may notice that the IT function is used instead of the test function. It is a common alias. Running it === test returns true.

Grouping tests like this makes the code cleaner. You should care about the quality of the program code and the code being tested against it.

In addition to making the code more readable, it helps to provide friendlier error messages if problems occur. If you change the test to include expect(typeof Math.random()).toequal (‘string’), you see the following message:

FAIL. / math. Test. Js lowinThe Math Global Object › The RandomfunctionHolds the shouldreturn a number
 
    expect(received).toEqual(expected)
 
    Expected value to equal:
      "string"
    Received:
      "number"
Copy the code

conclusion

As an introduction, we’ve explained the most basic types of JavaScript tests. The first category of tests covered is “unit tests.” To implement them, we’ve looked at the basics of the Jest framework. It includes information on how to run tests (installation and file naming). To run the tests, we used the Test, IT, and Describe functions.

Welcome to the front end public number: front end pioneer, free to receive Webpack tutorial.