如何SpyOn本机JavaScript函数?如.find()?

时间:2019-07-08 11:00:07

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

我尝试在以下情况下嘲笑this.editedComponentDetailsData.find

editButtonClicked(event) {
    let rowData = this.editedComponentDetailsData.find((row) => {
      return row.operationalSequenceNumber == this.rowKey;
    })
  }

这不起作用:

 it('should do something', () => {
    let result=spyOn(subject.editedComponentDetailsData.prototype,'find').and.returnValue({prop1:''});
  });

1 个答案:

答案 0 :(得分:2)

只需为editedComponentDetailsData分配一个像空数组一样可迭代的属性,然后您就可以监视一下find,但是就像在组件内部一样,您无需原型就可以访问它。

beforeEach(() => {
    TestBed.resetTestEnvironment();
    TestBed.initTestEnvironment(BrowserDynamicTestingModule,
      platformBrowserDynamicTesting())

    TestBed.configureTestingModule({
      declarations: [AppComponent],
      providers: [
        AppComponent
      ],

      schemas: [NO_ERRORS_SCHEMA]
    });
    fixture = TestBed.createComponent(AppComponent);
    subject = fixture.componentInstance;
    subject.editedComponentDetailsData=[]; //mock with empty array
  });
  it('should do something', () => {
    let result=spyOn(subject.editedComponentDetailsData,'find').and.returnValue({prop1:''}); //the spy
  });