Mocking angular service class properties or variables
Asked Answered
P

1

6

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]'
  }
}));
Prohibitory answered 3/10, 2017 at 17:6 Comment(0)
A
5

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);
});
Anaphora answered 20/6, 2018 at 11:59 Comment(1)
you can override only the property you need and keep the service by using: class MockConfigService extends ConfigService { ..}Suellensuelo

© 2022 - 2024 — McMap. All rights reserved.