Stub file imports in Angular 2+ Unit Testing

303 views Asked by At

My project has a lot of utility functions that perform some data transformations, etc. These functions are not in class and are reused in many utility files.

I'm very new to angular testing. Searched for quite some time and I couldn't find a way to stub the imports of a tested file. Here's the example:

/utils/helpers.ts

export const sumNumber = (a: number, b: number): number => {
  return a + b;
}

/utils/file-i-want-to-test.ts

import { sumNumber } from "./helpers";

export const sumArrays = (arr1: number[], arr2: number[]): number[] => {
  const len = arr1.length > arr2.length ? arr1.length : arr2.length;
  const result = new Array(len).fill(0);

  return result.map((_, index) => sumNumber(arr1[index] || 0, arr2[index] || 0));
}

/utils/file-i-want-to-test.spec.ts

import { sumArrays } from './file-i-want-to-test';

describe('Utilities', () => {

  describe('Function - sumArrays', () => {

    it('should return empty array', () => {
      const actual = sumArrays([], []);
      expect(actual).toEqual([]);
    });

    it('should call sumValue 2 times', () => {
      const actual = sumArrays([1, 2], [3, 4]);

      // How to test that sumArray is actually calling his dependency sumNumber?
    });
  });
});

Problem

In order to unit test function sumArrays properly, I need to stub it's dependency sumNumber. How it can be done?

1

There are 1 answers

1
AliF50 On

Try this:

import * as helpers from './helpers'; // import helpers like so

describe('Utilities', () => {

  describe('Function - sumArrays', () => {

    it('should return empty array', () => {
      const actual = sumArrays([], []);
      expect(actual).toEqual([]);
    });

    it('should call sumValue 2 times', () => {
      spyOn(helpers, 'sumNumber'); // this just stubs it to return undefined
      const actual = sumArrays([1, 2], [3, 4]);
      expect(helpers.sumNumber).toHaveBeenCalled(); // expect it was called
      // How to test that sumArray is actually calling his dependency sumNumber?
    });
  });
});

The spyOn has a richer API as well, spyOn just makes it return undefined.

spyOn(helpers, 'sumNumber').and.callFake(/* your fake function here */); // can call fake so every time sumNumber is called, you can have your own definition of a function

spyOn(helpers, 'sumNumber').and.returnValue(2) // always return 2 when sumNumbers is called

// also can see how many times it was called expect(helpers.sumNumber).toHaveBeenCalledTimes(2); // called twice // can see with what it has been called with expect(helpers.sumNumber).toHaveBeenCalledWith([1, 2]); // 1 being a, 2 being b