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

发布时间:2019-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了使用angular中的单元测试,脱离后台独立开发(二)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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

本文中,我们继续这一话题,以期望能够进一步简化我们的单元测试。

面临问题

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

解决方案

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

  • 先定义别一个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();
    });
});

测试:

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

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

然后:在其它的测试中,如果你还需要这个CollegeService,使用以上方法将测试用的CollegeTestService注入就好了。

TODO

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

脚本宝典总结

以上是脚本宝典为你收集整理的使用angular中的单元测试,脱离后台独立开发(二)全部内容,希望文章能够帮你解决使用angular中的单元测试,脱离后台独立开发(二)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。