derrickrozay
derrickrozay

Reputation: 1046

How to correctly call function from unit test

When running a code coverage test it says that the function clearAllValues is not being executed in the test but I am calling this function in my tests below

code coverage

tests

it('clearAllValues should be called by click', () => {
  spyOn(component, 'clearAllValues');
  const button = fixture.debugElement.query(By.css('.clearAllValuesBtn')).nativeElement;
  button.click();
  fixture.whenStable().then(() => {
    expect(component.clearAllValues).toHaveBeenCalled();
    expect(component.value).toEqual('');
    expect(component.allowReset).toEqual(false);
    expect(component.term).toEqual('');
  });
});

it('should call clearAllValues function', () => {
  spyOn(component, 'clearAllValues');
  component.clearAllValues();
  expect(component.clearAllValues).toHaveBeenCalled();
});

component

clearAllValues = () => {
  this.value = '';
  this.allowReset = false;
  this.term = '';
}

Upvotes: 4

Views: 2315

Answers (1)

nash11
nash11

Reputation: 8650

In unit testing, while testing a particular method/function we may not always want to call through all the other dependent methods/functions. Jasmine provides the spyOn() function for such purposes.

As per this definition, we only need to use a spy for your first test. When the button is clicked, we just want to find out whether clearAllValues was called, We're not bothered about what the function actually does. That part can be tested separately. See the docs to know when you need to use spies.

In your first test clearAllValues should be called by click, you need to do just that, i.e. check if clearAllValues was called. You need to use a spy for this test to find out if the function was called or not.

it('clearAllValues should be called by click', () => {
    const button = fixture.debugElement.query(By.css('.clearAllValuesBtn')).nativeElement;
    spyOn(component, 'clearAllValues');
    button.click();
    fixture.whenStable().then(() => {
        expect(component.clearAllValues).toHaveBeenCalled();
    });
});

Then when you are actually testing clearAllValues, that's when you need to check whether your variables have been set or not.

it('should clear values when clearAllValues is called', () => {
    component.clearAllValues();
    expect(component.value).toEqual('');
    expect(component.allowReset).toBeFalsy();
    expect(component.term).toEqual('');
});

Upvotes: 2

Related Questions