使用JEST测试角度组件

时间:2020-04-25 07:08:32

标签: javascript angular typescript unit-testing jestjs

我最近开始在Angular中使用JEST,但我找不到一个明确的示例,因此想在这里分享,这样可以对其他人有所帮助。

我有以下AppComponent.ts:

import { Component, OnInit } from '@angular/core';
import { ApiService } from './services/api.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {

  public title = 'jestTest';
  public jsonData = [];

  constructor(private apiService: ApiService) { }

  ngOnInit() {
    this.apiService.getData().subscribe((data: []) => {
      if (data) {
        this.jsonData = data;
      } else {
        this.jsonData = [];
      }
    });
  }

}

注入一个简单的http服务以从数据库中获取一些记录,并具有一个变量'title'。在组件初始化时,我进行了调用并获得了结果。

在我的HTML中,我只是显示测试:

<div> 
  <span>{{ title }}</span>
  <router-outlet></router-outlet>
</div>

这是spec.ts文件:AppComponent.spec.ts:

import { render } from '@testing-library/angular';
import { AppComponent } from './app.component';
import { async, TestBed, ComponentFixture, inject } from '@angular/core/testing';
import { AppRoutingModule } from './app-routing.module';
import { APP_BASE_HREF } from '@angular/common';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { ApiService } from './services/api.service';
import { of } from 'rxjs';

const dataArray = [
  {
    object1: 'Object one'
  },
  {
    object2: 'Object two'
  },
  {
    object3: 'Object three'
  }
];

const mockAPIService = {
  getData: jest.fn()
};

describe('AppComponent', () => {
  let component: AppComponent;
  let service: ApiService;
  let fixture: ComponentFixture<AppComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [
        AppRoutingModule,
        HttpClientTestingModule
      ],
      providers: [
        { provide: APP_BASE_HREF, useValue: '/' },
        { provide: ApiService, useValue: mockAPIService },
      ]
    })
      .compileComponents();
  }));

  afterEach(() => {
    if (fixture) {
      fixture.destroy();
    }
    mockAPIService.getData.mockReset();
  });

  it('should render the component', async () => {
    mockAPIService.getData.mockImplementationOnce(() => of(dataArray));
    const { getByText } = await render(AppComponent);
    expect(getByText('jestTest'));
  });

  it('Service injected via inject(...) and TestBed.get(...) should be the same instance',
    inject([ApiService], (injectService: ApiService) => {
      service = TestBed.get(ApiService);
      expect(injectService).toBe(service);
    })
  );

  it('should return a list if data available', async () => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    mockAPIService.getData.mockImplementationOnce(() => of(dataArray));
    component.ngOnInit();
    expect(component.jsonData.length).toBeGreaterThanOrEqual(1);
  });

  it('should return a empty list if no data available', async () => {
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.componentInstance;
    mockAPIService.getData.mockImplementationOnce(() => of(null));
    component.ngOnInit();
    expect(component.jsonData.length).toEqual(0);
  });

});

代码覆盖率指出第14行未覆盖。也就是说,构造函数(私有apiService:ApiService){}

------------------------|---------|----------|---------|---------|-------------------
File                    | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------------------|---------|----------|---------|---------|-------------------
All files               |     100 |       80 |     100 |     100 |                  
 app                    |     100 |    83.33 |     100 |     100 |                  
  app.component.html    |     100 |      100 |     100 |     100 |                  
  app.component.ts      |     100 |    83.33 |     100 |     100 | 14            

为什么不包括在内?

如果可以进行验证,以便其他人也可以将其推荐给他们进行单元测试,那将是很棒的事情。

0 个答案:

没有答案
相关问题