Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • SpyOn doesn't work because function is not attached to anything

  • Importing an mock-function into the imports array of TestBed.configureTestingModule gives Unexpected value 'doSomething' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.

  • Creating a service for it works but it feels silly to have to create services for each imported function

like image 948
user7995820 Avatar asked May 30 '18 12:05

user7995820


People also ask

How do you mock an imported function?

To mock an imported function with Jest we use the jest. mock() function. jest. mock() is called with one required argument - the import path of the module we're mocking.

How do you mock a service to inject in a unit test?

var service = new MockLoginService(); beforeEachProviders(() => [ provide(TestService, { useValue: service })]); it('should load languages', inject([TestComponentBuilder], (tcb: TestComponentBuilder) => { tcb . createAsync(LoginComponent). then((fixture) => { let element = fixture.

What is mocking in unit testing Angular?

Introduction. Mocking is a great idea for testing Angular apps because it makes maintenance easier and helps reduce future bugs. There are a few complex tools, such as XUnit, for mocking an Angular CLI project. You can execute the mocking methods described in this guide only if you use vanilla Jasmine + Angular Testbed ...


1 Answers

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({}); 
like image 137
MDI Avatar answered Oct 13 '22 06:10

MDI