简体   繁体   中英

How to SpyOn native JavaScript functions? Such as .find()?

I am trying to mock this.editedComponentDetailsData.find in the following :

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

This doesn't work:

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

Just assign to the editedComponentDetailsData an property which is iterable like an empty array and then you can spy on find, but you just access this without the prototype just like inside your component.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM