028-86922220

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

Angular单元测试编写的技巧有哪些

这篇“Angular单元测试编写的技巧有哪些”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“Angular单元测试编写的技巧有哪些”文章吧。

创新互联从2013年创立,公司以成都网站制作、成都做网站、系统开发、网络推广、文化传媒、企业宣传、平面广告设计等为主要业务,适用行业近百种。服务企业客户超过千家,涉及国内多个省份客户。拥有多年网站建设开发经验。为企业提供专业的网站建设、创意设计、宣传推广等服务。 通过专业的设计、独特的风格,为不同客户提供各种风格的特色服务。

Angular单元测试编写的技巧有哪些

测试思路:

单元测试

其中component,默认是Angular使用以下语法创建的待测试对象的instance

beforeEach(() => { 
  fixture = TestBed.createComponent(BannerComponent); 
  component = fixture.componentInstance; 
  fixture.detectChanges(); 
});

函数测试

1.函数调用,且没有返回值

function test(index:number ,fn:Function){
 if(fn){
     fn(index);
 }
}

请问如何测试?

反例: 直接测试返回值undefined

  const res = component.test(1,() => {}));
  expect(res).tobeUndefined();

推荐做法:

 # 利用Jasmine
 it('should get correct data when call test',() =>{
     const param = {
       fn:() => {}
    }
   spyOn(param,'fn')
   component.test(1,param.fn);
   expect(param.fn).toHaveBeenCalled();
 })

结构指令HostListener测试

结构指令,常用语隐藏、显示、for循环展示这类功能

 # code
 @Directive({ selector: '[ImageURlError]' })
export class ImageUrlErrorDirective implements OnChanges {
  constructor(private el: ElementRef) {}
  
  @HostListener('error')
  public error() { 
      this.el.nativeElement.style.display = 'none';
  } 
}

如何测试?

测试思路:

#1.添加一个自定义组件, 并添加上自定义指令
@Component({
  template: `
       
` }) class TestHostComponent { } #2.把自定义组件视图实例化,并派发errorEvent beforeEach(waitForAsync(() => {     TestBed.configureTestingModule({         declarations: [             TestHostComponent,             ImageURlError         ]     }); })); beforeEach(() => {   fixture = TestBed.createComponent(TestHostComponent);   component = fixture.componentInstance;   fixture.detectChanges(); });    it('should allow numbers only', () => {     const event = new ErrorEvent('error', {} as any);     const image = fixture.debugElement.query(By.directive(ImageURlError));     image.nativeElement.dispatchEvent(event); //派发事件即可,此时error()方法就会被执行到 });

善用 public,private,protected 修饰符

angular中public修饰的,spec.ts是可以访问到;但是 private,protected修饰的,则不可以;

敲黑板

测试click 事件

click事件的触发,有直接js调用click,也有模仿鼠标触发click事件。

# xx.component.ts
@Component({
 selecotr: 'dashboard-hero-list'
})
class DashBoardHeroComponent {
    public cards = [{
        click: () => {
            .....
        }
    }]
}
# html

`

如何测试?

测试思路:

it('should get correct data when call click',() => {
    const cards = component.cards;
    cards?.forEach(card => {
        if(card.click){
            card.click(new Event('click'));
        }
    });
    expect(cards?.length).toBe(1);
});

其余 click 参考思路:

思路一:

思路二:

以上就是关于“Angular单元测试编写的技巧有哪些”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注创新互联行业资讯频道。


网站名称:Angular单元测试编写的技巧有哪些
网页链接:http://www.tsicrk.com/article/jsgdeo.html

其他资讯

让你的专属顾问为你服务

1.1241s