簡體   English   中英

使用 Jasmine 使用 rxjs 主題對 Angular 組件進行單元測試

[英]Unit Testing Angular components with rxjs Subjects using Jasmine

我有兩個組件和一個服務層。 服務層在其中聲明了一個帶有 set 和 get 方法定義的主題。 第一個組件基於用戶操作調用主題的 set 方法,而第二個組件訂閱相同的主題。 它工作得很好,但是當我嘗試在第二個組件中對訂閱進行單元測試時,我在使用該方法時遇到了問題。 我創建了一個模擬服務層來測試其他功能。

ngOnit 中的訂閱在測試運行期間沒有受到影響。 代碼在組件初始化時在訂閱內執行,但不在調用 setSubject 之后執行。 當我調試時,我可以看到它在執行完成后命中,但我無法驗證數據是否更新。

export class MockService {
 private subject = new Subject<any>();

 getSubject() {
   return Observable.of(this.subject);
 }

 setSubject(value) {
   this.subject.next({ message: value });
 }

}

組件 2

export class Component2 implements OnInit {
  textFromComponent1: string;
  subscription: Subscription;

  constructor(public service: Service) {}
  ngOnInit() {
    this.subscription = this.service.getSubject().subscribe(message => {
      this.textFromComponent1 = message.value;
    });
  }
}

組件 2 單元測試

beforeEach( async(() => {
    TestBed.configureTestingModule( {
        declarations: [Component2],
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        providers: [{ provide: Service, useClass: MockService }]
    } )
        .compileComponents();
} ) );
beforeEach(() => {
    fixture = TestBed.createComponent( Component2 );
    component = fixture.componentInstance;
    fixture.detectChanges();
});
it('should test subscription' () => {
   component.service.setSubject("abc");
   expect(component.textFromComponent1).toBe("abc");
});

由於Subject是一種特殊類型的Observable ,因此您應該從getSubject()方法返回this.subject ,而不是使用Observable.of()方法將其包裝到observable

這是一個使用angular v11+ 的工作示例:

example.component.ts

import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs';
import { Service } from './example.service';

@Component({})
export class Component2 implements OnInit {
  textFromComponent1: string;
  subscription: Subscription;

  constructor(public service: Service) {}
  ngOnInit() {
    console.log('ngOnInit');
    this.subscription = this.service.getSubject().subscribe((data) => {
      console.log(data);
      this.textFromComponent1 = data.message;
    });
  }
}

example.service.ts

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class Service {
  private subject = new Subject<{ message: string }>();

  getSubject() {
    return this.subject;
  }

  setSubject(value: string) {
    this.subject.next({ message: value });
  }
}

example.component.spec.ts

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { Subject } from 'rxjs';
import { Component2 } from './example.component';
import { Service } from './example.service';

class MockService {
  private subject = new Subject<any>();

  getSubject() {
    return this.subject;
  }

  setSubject(value: string) {
    this.subject.next({ message: value });
  }
}

fdescribe('52263178', () => {
  let fixture: ComponentFixture<Component2>;
  let component: Component2;
  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [Component2],
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        providers: [{ provide: Service, useClass: MockService }],
      }).compileComponents();
    })
  );
  beforeEach(() => {
    fixture = TestBed.createComponent(Component2);
    component = fixture.componentInstance;
  });

  it(
    'should test subscription',
    waitForAsync(() => {
      expect(component.textFromComponent1).toBeUndefined();
      fixture.detectChanges();
      component.service.setSubject('abc');
      fixture.whenStable().then(() => {
        expect(component.textFromComponent1).toBe('abc');
      });
    })
  );
});

單元測試結果:

✔ Browser application bundle generation complete.
LOG: 'ngOnInit'
Chrome Headless 80.0.3987.87 (Mac OS 10.13.6): Executed 0 of 33 SUCCESS (0 secs / 0 secs)
LOG: Object{message: 'abc'}
Chrome Headless 80.0.3987.87 (Mac OS 10.13.6): Executed 0 of 33 SUCCESS (0 secs / 0 secs)
Chrome Headless 80.0.3987.87 (Mac OS 10.13.6): Executed 2 of 33 (skipped 31) SUCCESS (0.152 secs / 0.071 secs)
TOTAL: 2 SUCCESS

測試覆蓋:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM