SamuraiJack
SamuraiJack

Reputation: 5549

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

Upvotes: 0

Views: 123

Answers (1)

Erbsenkoenig
Erbsenkoenig

Reputation: 1659

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

Upvotes: 2

Related Questions