簡體   English   中英

茉莉功能間諜不適用於角

[英]Jasmine function Spy doesn't work with angular

我有一個帶有以下測試套件的angular-cli項目:

let fakeCellService = {
  getCellOEE: function (value): Observable<Array<IOee>> {
    return Observable.of([{ time: moment(), val: 67 }, { time: moment(), val: 78 }]);
  }
};

describe('Oee24Component', () => {
  let component: any;
  let fixture: ComponentFixture<Oee24Component>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [Oee24Component],
      providers: [{ provide: CellService, useValue: fakeCellService }]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(Oee24Component);
    component = fixture.componentInstance;
    fixture.detectChanges();
    spyOn(fakeCellService, 'getCellOEE');
  });

  it('should get cell oee on init', () => {
    component.ngOnInit();
    expect(fakeCellService.getCellOEE).toHaveBeenCalled();
  });
});

但是,測試中的間諜失敗。 我知道該函數被調用,因為我在調試器中對此進行了測試。 我看不出這與已記錄的示例有何不同,但大概可以! 有什么想法嗎?

這是我的組件:

@Component({
  selector: 'app-oee',
  templateUrl: './oee.component.html',
  styleUrls: ['./oee.component.css']
})
export class Oee24Component implements OnInit {

  constructor(public dataService: CellService) { }

  ngOnInit() {
    this.dataService.getCellOEE(this.cell).subscribe(value => this.updateChart(value));
  }

  updateChart(data: Array<IOee>) {
      //Logic here
  }
}

首先注入Injector

 import { Injector } from '@angular/core';
 import { getTestBed } from '@angular/core/testing';

創建服務變量(在您的組件變量下面)

let service : CellService;
let injector : Injector;

在測試平台處理之后將其注入(就在您的組件實例下方)

injector = getTestBed();
service = injector.get(CellService)

現在你可以監視它

spyOn(service, 'YourMethod').and.returnValue({ subscribe: () => {} });

讓我知道您的工作描述部分代碼是否有任何混淆

describe('Oee24Component', () => {
 let component: any;
 let fixture: ComponentFixture<Oee24Component>;
 let injector: Injector;
 let service: CellService;


 beforeEach(async(() => {
  TestBed.configureTestingModule({
   declarations: [Oee24Component],
   providers: [{ provide: CellService, useValue: fakeCellService }]
  })
  .compileComponents();
 }));

 beforeEach(() => {
  fixture = TestBed.createComponent(Oee24Component);
  component = fixture.componentInstance;
  injector = getTestBed();
  service = injector.get(CellService)
  fixture.detectChanges();
  spyOn(service, 'getCellOEE').and.returnValue({ subscribe : () => {} });
 });

 it('should get cell oee on init', () => {
  component.ngOnInit();
  expect(service.getCellOEE).toHaveBeenCalled();
 });
});

暫無
暫無

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

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