使用angular中的单元测试,脱离后台独立开发(二)

前文中,咱们展现了在单元测试中,如何注入依赖,并改写依赖中特定方法中的返回值。从而达到脱离后台,独立开发前台的目的。segmentfault

本文中,咱们继续这一话题,以指望可以进一步简化咱们的单元测试。antd

面临问题

有些服务,咱们可能须要在多个组件中调用。若是按上文的方法,那么就须要在多个组件的单元测试中,重复去定义模拟返回的数据。显然,若是是这样,咱们便制造了重复的轮子。async

解决方案

写一个专门用来测试的服务,使其可以在全部的单元测试中应用,而不在生产环境中应用。运用的知识固然是重写了。
仍然以CollegeService为例。为了解决单元测试请求真实后台的问题,咱们:ide

  • 先定义别一个CollegeTestService,使其继承CollegeService,这样其便有了CollegeService的全部的方法,并且能够任意的去重写CollegeService中的方法。
  • 在单元测试时,将CollegeTestService注入,以替换CollegeService

编码

CollegeTestService 用于测试的服务类单元测试

import {Injectable} from '@angular/core';
import {Observable, of} from 'rxjs';
import {College} from '../entity/college';
import {CollegeService} from './college.service';
import {Page} from '../entity/page';

@Injectable({
    providedIn: 'root'
})
export class CollegeTestService extends CollegeService {
    /**
     *获取分页数据
     */
    getCollegeByPage(page: number, size: number): Observable<Page<College>> {
        // 初始化变量
        const dataPage = new Page<College>();
        dataPage.content = new Array<College>(
            College.instance()
        );

        // 定义观察者
        const observable = of(dataPage);

        return observable;
    }
}

单元测试

import {async, ComponentFixture, inject, TestBed} from '@angular/core/testing';

import {CollegeIndexComponent} from './college-index.component';
import {NzGridModule, NzDividerModule, NzTableModule, NzFormModule} from 'ng-zorro-antd';
import {HttpClientModule} from '@angular/common/http';
import {RouterTestingModule} from '@angular/router/testing';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {CollegeService} from '../../../../../service/college.service';
import {CollegeTestService} from '../../../../../service/college-test.service';

/**
 * 对测试的描述:CollegeIndexComponent
 */
describe('CollegeIndexComponent', () => {
    // 定义两个变量
    let component: CollegeIndexComponent;
    let fixture: ComponentFixture<CollegeIndexComponent>;

    beforeEach(async(() => {
        // TestBed工做台
        // TestBed.configureTestingModule 配置要测试的模块
        // 这贴近于现实生活。现实生活中,咱们测试一块电表是否正确.
        // 1. 须要一个专门用于测试的工做台
        // 2. 须要对这个测试的工做进行配置,以让其符合测试电表的基础工做
        TestBed.configureTestingModule({
            // 声明要上工做台的组件
            declarations: [CollegeIndexComponent],
            // 配置测试的依赖,没有这些模块,测试就进行不了。
            // 好比咱们测试电表是否准确,须要有交流电,须要有电流表,须要有电压表等
            imports: [NzGridModule,
                HttpClientModule,
                NzDividerModule,
                NzTableModule,
                RouterTestingModule,
                ReactiveFormsModule,
                FormsModule,
                NzFormModule],
            // 定义providers ** 这是重点 **
            providers: [
                {
                    provide: CollegeService,
                    useClass: CollegeTestService
                } // 使用 CollegeTestService 来替换 CollegeService ** 这是重点 **
            ]
        }).compileComponents(); // 配置完后,开始编译要测试组件
    }));

    /**
     *  每次测试前,均执行一遍
     *  inject([], () => {}) 单元测试中的方法
     *  CollegeService 要注入的服务
     *  collegeService为服务起的别名,类型为CollegeService,其对应注入的第一个参数
     */
    beforeEach(inject([CollegeService], (collegeService: CollegeService) => {
        // 打印,查看究竟是哪一个 service 被注入了
        console.log(collegeService);

        // fix = 固定。用工做台建立一个供测试的组件。
        // 因为其想要被测试,就必然还须要其它的一些脚手架。
        // 咱们把脚手架与被测试的组件组成的联合体称为:ComponentFixture 被固定的组件
        fixture = TestBed.createComponent(CollegeIndexComponent);

        // 实例化要测试的组件
        component = fixture.componentInstance;

        // 检测变化
        fixture.detectChanges();
    }));

    /**
     * 测试方法的描述信息:should create
     */
    it('should create', () => {
        // 期待 组件 被成功建立
        expect(component).toBeTruthy();
    });
});

测试:测试

clipboard.png

clipboard.png

而后:在其它的测试中,若是你还须要这个CollegeService,使用以上方法将测试用的CollegeTestService注入就行了。编码

TODO

是时候来启用接口了,你说呢?spa

相关文章
相关标签/搜索