0%

angular pipe testing

angular pipe testing

angular 2 中管道功普遍使用,针对管道方面的单元测试当前写法各有不一。关于管道的集成单元测试和
独立单元测试,有两篇不错的文章可参考。独立单元测试
集成单元测试

什么是集成单元测试,什么是独立单元测试?

独立单元测试即只测试函数本身,集成单元测试即加入其他相关元素端到端测试

针对管道来说,什么时候用集成单元测试,什么时候用独立单元测试

对于无状态的管道来说,可以选择独立单元测试
对于输入和输出受到其他变量影响的情况下,选择集成单元测试

管道的独立单元测试如何去写?

一、构建执行环境
  1. 管道声明
  2. 创建管道实例
  3. 检查管道是否被实例化
    执行环境
    二、测试用力编写
  4. 异常值的输入输出用力测试
  5. 一般值输入输出
    用力编写

管道如何构建集成单元测试?

一、求平均值的管道
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'mean'
})
export class MeanPipe implements PipeTransform {

transform(value: number[]): number {
if (!Array.isArray(value)) {
return value;
}
if (value.length === 0) {
return undefined;
}
const sum = value.reduce((n: number, m: number) => n + m, 0);
return sum / value.length;
}
}
二、构建测试环境
  1. TestBed.configureTestingModule 创建模块,类似@NgModule
  2. 集成测试依赖异步变异 beforeEach中执行TestBet.compileComponents 同事回调用async
  3. 宿主组建依赖执行环境,执行环境中包含一些诸如脏检查等的方法 ComponentFixture 封装组建
  4. fixture是由TestBed.createComponent 创建的
  5. 在fixture中调用DebugElement类的一些方法
  6. 测试fixture 被正确实例化。
    构建执行环境
三、测试用力全部代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { MeanPipe } from './mean.pipe';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';

@Component({
template: '<div>{{ values | mean }}</div>'
})
export class MeanPipeHostComponent {
values: number[];
}

describe('MeanPipe inside a Component', () => {
beforeEach(async(() => {
TestBed
.configureTestingModule({
declarations: [MeanPipe, MeanPipeHostComponent]
})
.compileComponents();
}));

let fixture: ComponentFixture<MeanPipeHostComponent>;
let debugElement: DebugElement;
let component: MeanPipeHostComponent;

beforeEach(() => {
fixture = TestBed.createComponent(MeanPipeHostComponent);
debugElement = fixture.debugElement;
component = fixture.componentInstance;
});

it('should create an instance', () => {
expect(fixture).toBeTruthy();
});

it('should display 1', () => {
component.values = [1, 1];
fixture.detectChanges();

const div: HTMLDivElement = debugElement
.query(By.css('div'))
.nativeElement;

expect(div.textContent.trim()).toEqual('1');
});

it('should display 0', () => {
component.values = [1, -1];
fixture.detectChanges();

const div: HTMLDivElement = debugElement
.query(By.css('div'))
.nativeElement;

expect(div.textContent.trim()).toEqual('0');
});

it('should display nothing', () => {
component.values = [];
fixture.detectChanges();

const div: HTMLDivElement = debugElement
.query(By.css('div'))
.nativeElement;

expect(div.textContent.trim()).toEqual('');
});
});