DevUI is a team with both design and engineering perspectives, serving huawei DevCloud platform and huawei internal background systems, as well as designers and front-end engineers. Add devui Helper (Devui-Official) DevUIHelper plugin: Devuihelper-lsp (welcome Star)

The introduction

Business requirements change rapidly, involve a large amount of UI and interaction, and most business scenarios exchange and process data with the back end. These facts make testing a huge headache for the front end, and an excuse for the front end not to write unit tests.

When we’re faced with a less familiar territory or scenario, it’s easier to get our foot in the door with something simple and quick to implement. That’s the purpose of this article, to get you through the spike of unit tests and porting them to the project code in less than 20 minutes.

This paper consists of three parts:

(1) Why write tests that contain many common beliefs, misconceptions, and strategies about testing

(2) How to write the test? See the composition of a typical test through spike

(3) 20 minutes to integrate unit tests into existing projects

01 Why write tests?

Writing tests is good

Unit tests are difficult to write because of the special nature of the front-end business. I haven’t written a test for so long, and it feels okay. In addition, with so much demand for each iteration, business development is already a struggle. I had never written a unit test because OF this belief.

Note: All tests mentioned later in this article are unit tests if not prefixed. Unit tests are fast to execute and have wide coverage. According to the test pyramid principle, unit test coverage should be 100%!

After reading refactoring, JavaScript Test-Driven Development, and The Google Way of Software Testing, I found reasons to start writing tests:

(1) Tests are living documentation. Code is meant to be read, and tests are easier to understand than comments;

(2) Testing facilitates refactoring. Unit-tested code has lower operating costs when it extends functionality and refactorings.

(3) Testing can improve code quality. Once you start writing tests, you’ll see how disorganized your code is, forcing yourself to design from the source to solve problems, write testable code, and reduce cyclomatic complexity.

The cyclomatic complexity of code has been described in an article written by a colleague on the team. If you are interested, please refer to: juejin. Im /post/684490…

Another amazing tidbit about cyclomatic complexity. Uncle Bob says the ideal method should be no longer than four lines of code. That’s right, Uncle Bob, the author of Professional Programmer, a book that you can read no matter what time of day. If you haven’t read it yet, wall Crack recommends.

Given this, I decided to write unit tests for my project, and I already had a vague idea of how to do it.

Why it’s so hard for anyone to get started

There’s a lot of stuff going on here, but we all know that. “I know the truth, but I find it difficult to start.” So before we start, we need to answer two questions that are the reason most people put off writing tests:

Writing tests can be costly to the developer

To achieve or approach 100% unit test coverage, the amount of code would have to roughly double. FitNesse, a well-known acceptance testing tool, has 64,000 lines of code, 28,000 of which are unit tests (data from Programmer Professionalism). That’s a daunting ratio, and I used to be convinced that writing tests costs developers too much, until I came across this quote and shared it with you:

Someone will tell you that TDD reduces defects, but at a cost, you’ll write twice as much test code as production code, so it slows things down. The assumption is that the factor affecting software development is typing speed, but this is not true; it is actually reading requirements documents, writing documents, meeting, locating and fixing bugs.

This sentence will not be interpreted, we carefully taste.

Difficulties encountered by the front end in the testing area

Those are the questions that we mentioned in the introduction, which are very difficult to deal with from the above perspective. Let’s start with two other basic facts and see if we can improve.

(1) There are tools in every project that handle business logic common to several components, such as date-specific transitions, and so on. These methods are usually distributed in plain TS files or in services.ts

Pipe Angular projects use a lot of pipes. Pipes are logically stable functions that handle input and output. If you already have the name of the function in mind, let’s start with this section.

02 How do I get started?

Create a spike

A spike is when we are faced with a technical area that we are not familiar with, we throw away what we already have and build a demo from scratch quickly to see if our direction is feasible. Everyone has had the experience of using Spike to solve problems in their daily work, especially when it comes to technical rehearsal work. It’s just that many people don’t know how to describe the process.

Getting back to the body of work, most teams are probably faced with a situation where my code is currently working fine (at least not bad) and there are a lot of requirements to do per iteration. There was no tradition of writing tests on the team, and no one cared. It was a real hassle to integrate unfamiliar areas of technology into such a rapidly evolving project. So let’s make a spike first. Create a new project with ng-CLI to complete our exploration of Angular unit testing. In Spike, we can throw away all the constraints of specification and design, just for exploration and verification.

First, we create a new project using ng-CLI, which could not be simpler

ng new spike-test

Copy the code

then

cd spike-test
ng test

Copy the code

As above, we’ve done the simplest project involving unit tests that took you about three minutes? Now let’s take this project apart so we can extract the necessary information and integrate it into our existing projects.

See the composition of the test through Spike

Take a look at the file app.component.spec.ts

From this test file, we can see that to complete a test, we first import some test-related packages and the components being tested (or services, pipes, or even plain TS files).

A test suite (describe) will contain several should, which is the behavior that the test should verify, in this case the following three: app should be created, title should be spike-test, title should be rendered in h1 tag.

In addition to this, there are many related configuration files that need to be used. But overall, it’s pretty simple. So let’s go ahead and integrate test cases into existing projects.

03 How do I Integrate tests into existing Projects?

Install test dependencies and add related configuration files

All the problems encountered in this link, such as where to place the file and what the content of the file is, can be configured by referring to the Spike project we have done in the last section.

(1) Ensure that the karma. Conf.js configuration file is in the root directory

(2) make sure the test.ts file exists under SRC

(3) To ensure that your spec.ts file is not ignored by tsconfig, check the include and exclude configuration in the tsconfig file

(4) Ensure that the following dependencies are installed. If not, install them all first

"Karma", "^ 5.2.1", "karma - chrome - the launcher" : "^ 3.1.0", "karma - coverage - Istanbul - the reporter" : "^ 3.0.3", "karma - jasmine" : "^ 4.0.1", "karma - jasmine - HTML - reporter" : "^ 1.5.4",Copy the code

Let’s look at an example

Before we start, let’s go through the basic steps for writing test cases:

(1) First record the behavior you want to test through a handwritten list, that is, several should in the spike above

(2) Write test cases according to the above list

With the above dependencies and configuration in place, we can start to try to write test cases in our existing project. Suppose we have a method that converts bytes to common size representations (such as KB, MB, GB). The code for the method looks like this:

As mentioned above, let’s start by preparing the test behavior list:

  • Returns — when input is less than 0 or non-numeric
  • When the input is numeric and less than 100, the unit is B
  • When the input is an array and is greater than or equal to 100 but less than 100000, the unit is KB
  • . MB
  • . GB

Then start writing the test code for the public method by introducing the method into a new test file called test.spec.ts

import { transferSize } from './common-method';
Copy the code

Then add your test suite and a few Shoulds

describe('TransferSize Method Of Util', () => { it(`should return '--' when the input is less than zero`, () => { expect(transferSize(-1)).toEqual({ sizevalue: '--', sizeunit: '' }); }); it(`should return '--' when the input is not number`, () => { expect(transferSize('haha')).toEqual({ sizevalue: '--', sizeunit: '' }); }); it(`should return 'xB' when the input is less than 100`, () => { expect(transferSize(0)).toEqual({ sizevalue: '0', sizeunit: 'B' }) }); it(`should return 'xMB' when the input is more than 100`, () => { expect(transferSize(100)).toEqual({ sizevalue: '0.1', sizeUnit: 'KB'})}); it(`should return 'xGB' when the input is more than 100000`, () => { expect(transferSize(100000)).toEqual({ sizevalue: '0.1', sizeUnit: 'MB'})}); it(`should return 'xGB' when the input is more than 100000000`, () => {expect(transferSize(100000000)).toequal ({sizevalue: '0.1', sizeUnit: 'GB'})}); });Copy the code

That’s it, run ng test, done!

A simple unit test case has been integrated into our existing project.

If you also want to see code test coverage for each file in your project, you can run ng test –code-coverage. Of course, configure the coverage folder path in your Karma. Conf.js

Once configured, each time you run the command above, a more detailed result is generated in the coverage folder at the root of the project. Open the index.html file in the folder to see the test coverage and uncovered code for each file.

04 summary

In order to achieve fast implementation, this article only connected the necessary parts together to form a minimum operational demo. There are still many questions about testing, such as the calculation methods of various test coverage, how to use mock & Stub to test the interface interaction business. How to test against a component library scenario like DevUI.

See you next time for all the unanswered questions mentioned above.

Join us

We are DevUI team, welcome to come here and build elegant and efficient human-computer design/research and development system with us. Email: [email protected].

The text/DevUI east less

Previous articles are recommended

With these two things on the front end, you don’t have to chase the backend for the interface anymore.

Dark Mode and Thematic Development of Web Interfaces

“How to build a grayscale Publishing environment”