>>> Part 2 – Jasmine Grammar Introduction

>>> Part 3 – Angular unit Testing easy start

Recently, the development work of the project team was not tense, and the boss asked to write unit tests to make the coverage figure better. Personally, I scoff (secretly) at the idea of unit testing after feature development, but it’s an opportunity to learn, so I started studying Angular Tests…

First Step

Start with the simplest test project and initialize app-test

ng new app-test...
Copy the code

After the project is initialized, run the ng test command directly to run the default test code. I ran it directly on Angular CLI V6.0.7 and got an error about jasmine and typescript versions being inconsistent, testing a possible solution. After the error is resolved, you can run the unit test code by running ng Test. The browser will automatically open and display the test results.

How does Angular unit test?

Angular Testing relies on two things:

  • Karma Karma is a testing tool developed by Angular Team that checks and displays test results by starting a Web service, running test code and source code. Karma is automatically downloaded and installed when the project is initialized through angular-CLI. In the SRC directory of the project, the karma. Conf.js file is generated by default, which contains configuration information such as the default browser, root directory, port number, and so on, which can be changed according to actual needs. Please refer to the official introduction for details.

  • Jasmine Angular’s default unit test code is built based on the Jasmine test framework, a behavior-driven framework for testing javascript code. It works well with Karma. Similarly, Jasmine is also the official recommended testing framework, which is automatically downloaded and installed during project initialization.

.spec Indicates the basic structure of the test file

First, look at the default generated app.component.spec.ts file. After removing some necessary imports, the main contents of the test code are as follows:

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
  it(`should have as title 'app'`, async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('app');
  }));
  it('should render title in a h1 tag', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to app! ');
  }));
});
Copy the code

1. describe

The outermost layer is a method called ‘Describe’, which creates a collection of test cases declared as follows:

function describe(description: string, specDefinitions: () => void): void
Copy the code

The describe method takes two parameters: the first parameter is a string, which is the name of the test set and is displayed in the browser test report. The second parameter receives a callback, a set of test cases to execute.

2. beforeEach

The beforeEach method can be understood as preparing the test environment for each test case and is executed before the test case, declared as follows:

functionbeforeEach(action: ImplementationCallback, timeout? : number): void (+1 overload)Copy the code

BeforeEach is the method provided by the official API; BeforeEach, afterEach, beforeAll, afterAll, etc. See the official API for details.

3. it

The IT method is used to define a specific test case, and the test set defined by the Describe method should contain at least one IT method, that is, at least one test case.

functionit(expectation: string, assertion? : ImplementationCallback, timeout? : number): void (+1 overload)Copy the code

The IT method receives at least one parameter of type string, usually called an assertion, that is, the description of the test content for the use case, which will also be displayed in the test result report. “Should create the app” in the above example indicates that the purpose of the use case is to test the successful creation of the APP component. The second parameter is the specific test content; The third parameter sets its execution delay.

Write a simple test case

Once you understand the basic structure of the test code, try to write a test case that is as simple as possible. In general, pure method tests are the easiest, because you don’t know enough about them yet. To prevent interference, delete the default app.component.spec.ts file and empty app.component.html. Since there are no other test files in the project, running ng test shows the following:

Then, write a simple test case using a simple summation method as an example. Under SRC /app, create a folder named utils and create the convert.ts and convert.spec.ts files respectively under these folders, and type the following:

convert.ts

export class Convert {
    public static sum(x: number, y:number){
        returnx+y; }}Copy the code

convert.spec.ts

import { Convert } from './convert';
describe('Convert util testing', ()=>{
    it('should return sum of two', () = > {letresult = Convert.sum(1, 2); expect(result).toEqual(3); })})Copy the code

The above code implements the sum of two numbers of type number and builds a test case with a simple numeric test. Save the changes and run ng test to view the test result:

A very simple test is successful

Making: github.com/sunrun93/ap…

Of course, true Angular testing is much, much more complex… The official documentation is fairly comprehensive, but there is still a long way to go before it is fully understood. The journey of a thousand miles is based on kuibu. I hope I can continue to deepen, update, revise and continue to be continued…

>>> Part 2 – Jasmine Grammar Introduction

>>> Part 3 – Angular unit Testing easy start