无法在angular 6项目中使用Karma-jasmine测试工具测试动态内容

时间:2018-11-08 13:14:01

标签: angular unit-testing jasmine karma-jasmine karma-runner

  

在Angular 6和更高版本中为动态内容编写测试用例需要帮助   使用业力软件包。

规格:

  

我编写了用于检查文章视图的测试用例。之前   执行函数,它正在传递,但是在获取数据之后,   不及格。如何编写动态内容的测试用例。

describe('SingleArticleVideoComponent', () => {
    let originalTimeout;
  let debugTest: DebugElement[];
  let el: HTMLElement;
  let component: SingleArticleVideoComponent;
  let fixture: ComponentFixture<SingleArticleVideoComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SingleArticleVideoComponent,
          PollsComponent,
          AdBannerComponent],
        imports: [
            RouterTestingModule,
            NavModule,
        FooterModule,
            VgCoreModule,
            VgControlsModule,
            VgOverlayPlayModule,
            VgBufferingModule,
        FormsModule,
        ReactiveFormsModule,
        MatFormFieldModule,
        MatRadioModule,
        MatDialogModule,
            HttpModule,
            HttpClientModule,
            BrowserAnimationsModule,
            BrowserModule
        ],
        providers: [
            ArticleService,
            AdService,
            UserServiceService
        ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SingleArticleVideoComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
      originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
      jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000;
  });
    afterEach(function() {
        jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
        fixture = TestBed.createComponent(SingleArticleVideoComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });
    it('views should be more than 100', async(() => {
        expect(component.anchor).toEqual('before');
        expect(component.anchor).toEqual('after');
    }));
  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

component.ts:

  

使用 ng服务时,它给出的结果正确,但不是   使用 ng测试进行测试。

ngOnInit() {
     this.get_single_video('emcure-csi-tv-dr-pk-dep-ACE-inhibitor-or-ARNI-what-should-be-used-in-heart-failure-with-reduced-ejection-fraction', this.category);
}
get_single_video(slug, category) {
    console.log('get one video calling');
    this.anchor ='before';
    this.service.get_single_video(slug, category).subscribe(
      data => {
        if(data['success'])
        {
            this.anchor='after';
          this.load_data = true;
            if(data['data']['guest3'].length > 0 || data['data']['guest4'].length > 0){
                this.gus = true;
            }
        }
});

component.html:

  

当我控制台它时,Views给出null。视图显示正常   (如果我使用 ng服务而不是 ng测试运行)。

<li class="views"><code>{{single_article['anchor']}}</code><br>Views</li>

user-service.service.ts:

  

我可以在map函数中看到data.json(),但无法获取   在我提到的component.ts文件中的订阅函数中   以上。

import 'rxjs/Rx';
get_single_video(slug, catagory) {
    console.log('in article service single video');
    const final_url = this.api_url + '/' + slug + '?key=' + this.api_key;
    console.log(final_url);
    return this._http.get(final_url)
      .map(data => {
        data.json();
        // the console.log(...) line prevents your code from working
        // either remove it or add the line below (return ...)
        console.log(' I CAN SEE DATA HERE: ', data.json());
        return data.json();
      }).catch(error => observableThrowError(error.json()));
  }

enter image description here

2 个答案:

答案 0 :(得分:0)

通常,您不希望单元测试对后端进行http调用,而是模拟该功能。实际上,在组件测试中,您甚至想模拟服务的功能(这样,即使服务混乱了,组件单元测试也可以通过)。有关'ng test'和'ng e2e'之间的区别的详细说明,请参见以下问题的公认答案:question

假设您要在此阶段对组件进行单元测试,那么我将设置一个间谍来模拟您的服务调用并返回各种值,以便您可以通过“ get_single_video”组件方法的逻辑进行测试。我已经建立了一个STACKBLITZ来使用您自己的问题代码演示这一点。我设置了最少的代码来显示我的意思。 (MCVE

  

要注意的一件事-我从beforeEach()中拉出fixture.detectChanges()并将其放在'it'函数中。这是因为fixture.detectChanges()会调用ngOnInit(),并且需要在调用ngOnInit()之前设置服务调用的返回值,以便您可以控制逻辑路径。

从那堆闪电战中,这是我为测试两条路径而设置的描述。您应该能够对此进行扩展,以完整地了解您的功能。

describe('SingleArticleVideoComponent', () => {
    let component: SingleArticleVideoComponent;
    let fixture: ComponentFixture<SingleArticleVideoComponent>;
    let userServiceSpy = jasmine.createSpyObj('UserServiceService', ['get_single_video']);

    beforeEach(async(() => {
        TestBed.configureTestingModule({
          declarations: [ SingleArticleVideoComponent],
            providers: [
                { provide: UserServiceService, useValue: userServiceSpy }
            ]
        })
        .compileComponents();
    }));
    beforeEach(() => {
        fixture = TestBed.createComponent(SingleArticleVideoComponent);
        component = fixture.componentInstance;
    });

    it('should change anchor to "after" if get_single_video() has success set', () => {
        userServiceSpy.get_single_video.and.returnValue(of({success: 'yes', data: {guest3: ['1']}}));
        fixture.detectChanges();
        expect(component.anchor).toEqual('after');
    });
    it('should not change anchor if get_single_video() does not have success set', () => {
        userServiceSpy.get_single_video.and.returnValue(of({})); // Observable of an empty object
        fixture.detectChanges();
        expect(component.anchor).toEqual('before');
    });
});

答案 1 :(得分:0)

请勿测试API调用,并将其数据记录在单元测试中。回到组件,从fixture.detectChanges();beforeEach删除行it将为您提供对数据流的控制。 您可以添加模拟服务,

providers: [{ provide: UserServiceService, useValue: userServiceSpy }]

确保get_single_video服务间谍中有userServiceSpy,该服务间谍正在返回Observable类型的数据。

beforeEach方法中,通过在其中传递模拟服务来初始化该组件。例如

videoComponent = new SingleArticleVideoComponent(userServiceSpy)

您可以将此videoComponent用于测试用例。