user7995820
user7995820

Reputation: 442

How to mock/spy an imported function in Angular unit testing

Let's say i have an angular 6 component with a method test which returns some value:

import { doSomething } from './helper';

@Component({
    ...
})
export class AppComponent {
    test() {
        const data = doSomething(1);
        return data.something ? 1: 2;
    }
}

doSomething is just a simple helper function:

export function doSomething() {
    return { something: 1 };
}

Is it possible to mock or spy this function in a unit test (so i can control its returnValue)? Or do i have to change my approach in the component?

Please note: doSomething() can be a lodash function, a const, a class etc. I just tried to keep the example as simple as possible.


Things i've tried:

Upvotes: 38

Views: 41290

Answers (2)

RazvanParautiu
RazvanParautiu

Reputation: 2938

It is not possible to mock an external function, but you can do something like following which is working fine.

import { doSomething } from './helper';

@Component({
    ...
})
export class AppComponent {
    const doSomethingRef = doSomething; 
    test() {
        const data = this.doSomethingRef(1);
        return data.something ? 1: 2;
    }
}

Now, since we can mock doSomethingRef

describe('AppComponent ', () => {
  let appComponent: AppComponent ;
  beforeEach(() => {
    TestBed.configureTestingModule({});
    appComponent= TestBed.inject(AppComponent);
  });

  it('should allow mocking', () => {
    (appComponent as AppComponent).doSomethingRef = jasmine.createSpy('doSomethingRef ').and.returnValue(1);
    expect(guard.test()).toEqual(1);
  });
 }

Upvotes: 3

DarthJedi
DarthJedi

Reputation: 584

In your spec file import the helper this way:

import * as helper from './helper';

And in your it() you can spy on the helper object and return the requested value:

spyOn(helper, 'doSomething').and.returnValue({});

Upvotes: 46

Related Questions