Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking angular service class properties or variables

I am unit testing an angular application and there is a service I need to mock. I am able to mock service methods without any problem but when I try to mock properties in the same way it give me error

My configuration service have one property and one mothod, I want to mock the property as I cannot generate that value.

Service

@Injectable()
export class ConfigService {
  public config = 'iamdirect';

  constructor(private http: Http) {
   }

  public load(): Observable<any> {
    return 'Iamokey';
  }
}

Mocking the service in angular test

// mocking config service
configService = TestBed.get(ConfigService);
spyOn(configService, 'load')
  .and.returnValue(Observable.of({
  contactDetails: {
    emailAddress: '[email protected]'
  }
}));

When I do It gives me error.

spyOn(configService, 'config') //config is the property
  .and.returnValue(Observable.of({
  contactDetails: {
    emailAddress: '[email protected]'
  }
}));
like image 416
Aniruddha Das Avatar asked Oct 03 '17 17:10

Aniruddha Das


People also ask

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 ...

How do you unit test a service with a dependency?

Angular services can be tested in a couple of different ways, two most prominent being isolated tests and using the Angular TestBed . However, things get interesting when the service under test has dependencies (injected using Angular's dependency injection).

How do you mock a component in Angular unit testing?

A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.

What is the use of SpyOn in Angular?

Test the Component logic using SpyOn - Testing Angular. SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result. This example shows how spyOn works, even if we are still mocking up our service.


1 Answers

You can use jasmine to create a spy object or you can use a mock object as the service stub.

let mockConfigService;
let configService: ConfigService;
const subject = new Subject();

beforeEach(() => {

  mockConfigService = {
      config: 'test text',
      load: () => subject.asObservable()
  }

  TestBed.configureTestingModule({
   providers: [
      {provide: ConfigService, useValue: mockConfigService},
   ]
  });

  configService = TestBed.get(ConfigService);
});
like image 108
Anuradha Gunasekara Avatar answered Oct 23 '22 05:10

Anuradha Gunasekara