Spring
Spring

Reputation: 11

How can we mock (spyOn) a method call in typescript test case?

save() { .....

this.saveSelectedOnes();

..... }

I have already written a test case for saveSelectedOnes() method. While writing test case for save method, how can we skip the saveSelectedOnes() method call?

Upvotes: 1

Views: 385

Answers (1)

Jimmy Hedström
Jimmy Hedström

Reputation: 571

Depends on if the save method should returns something. In case of void:

  it('should call function', () => {
    const spy = spyOn(service, 'save'); 
    expect(service.save).toHaveBeenCalled(); 
  });

If you need to mock return data of the save method:

  it('should returns correct stuff', () => {
    const spy = spyOn(service, 'save').and.returnValue({status: 'saved}); 
    expect(service.save).toHaveBeenCalled(); 
  });

If you need to test parameters on the method:

  it('should test parameters', () => {
    const spy = spyOn(service, 'save');
    expect(service.save).toHaveBeenCalledWith('whatever parameter'); 
  });

In the same way, if you need to test if this.saveSelectedOnes() have been called within save() method, you can create a spy for that one too.

Upvotes: 1

Related Questions