繁体   English   中英

玩笑 + 角度 + 单元测试

[英]Jest + angular +unit test

我对使用 JEST 进行 Angular 测试非常陌生。 所以以下是我迄今为止尝试过的代码......

规格

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
//All import stuff here
describe('test1', () => {
    beforeEach(async(() => {
        const ngbActiveModalStub = { close: () => ({}) };
        //All my service stub goes here
        TestBed.configureTestingModule({      
          providers: [        
            mycomponent,
            { provide: NgbActiveModal, useValue: ngbActiveModalStub }]
        });
       component = TestBed.get(mycomponent)
    });
   it('should create', () => {
    expect(component).toBeTruthy();
  });
});

以上测试成功执行。 现在我想通过设置值来为独立功能编写测试用例。 考虑我在 ts 文件中有一个函数,如下所示:

组件.ts

updateValueInDropDown($event, i) {   
    
    if($event.target.value == 'abct') {      
      this.active= true;         
    } else {
      this.active= false;      
    }    
  }

abc() {    
if(this.active== true) {
   const value= this.form.value.xyz;
    this.service.validate(value).subscribe(
      (res)=>{
       },
      (error) => {
      });
  }
}

那么如何在测试用例中使active为真,以便调用以下 API 并在我的单元测试用例文件中测试此函数。 请分享您的想法。

您可以使用“component.variableName”为组件变量(“this”变量)设置值。

 it('test abc method', () => { // Set this.active to true component.active = true; // Rest of the testing.... });

在这种情况下,我会尝试做的是模拟用户的行为。 如果用户需要在下拉列表中选择某些内容来运行验证,那么我认为您也应该在测试中进行。 通过这种方式,您既可以记录组件的行为,又可以测试用户路径。

一个例子可能是:

describe('when the user selects "abct" on the dropdown', () => { // this description could be improved.

    beforeEach(() => {
        selectValue('abct');
        ...
    })

    it('should validate the provided value', () => {
        // see below
    })
})

function selectValue(value: string) {
    // Depending on the implementation of your dropdown (simple select element, a component from Angular Material or sth else) this may be different.
    // Maybe simply publishing the change event would suffice? See: https://stackoverflow.com/a/48947788/2842142
    fixture.debugElement.query(By.css('.dropdown'))
        .nativeElement
        .click();
    
    fixture.detectChanges();
    
    fixture.debugElement.queryAll(By.css('option'))
        .map(option => option.nativeElement)
        .find(option => option.innerText === value) // or option.value === value
        .click();
}

至于如何准确测试验证是否发生 - 您可能有不同的选择。 在大多数情况下,我会检查验证结果。 您可以查询 dom 中的一些更改或一些验证消息。

在某些情况下,提供模拟服务、监视调用( spyOn(service, 'validate') )并检查是否在测试期间调用了该方法( expect(service.validate).toHaveBeenCalledWith(expectedValue) )。 如果该服务在更多地方使用并编写了自己的测试,我会主要考虑它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM