茉莉花的功能间谍没有角度

时间:2017-03-30 16:07:26

标签: javascript angular typescript jasmine karma-jasmine

我有一个带有以下测试套件的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
  }
}

1 个答案:

答案 0 :(得分:1)

首先注入Injector

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

创建服务变量(在组件变量下面)

let service : CellService;
let injector : Injector;

在testbed进程之后注入它(在组件实例的正下方)

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();
 });
});