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: 'testemail@email.com'
  }
}));

When I do It gives me error.

spyOn(configService, 'config') //config is the property
  .and.returnValue(Observable.of({
  contactDetails: {
    emailAddress: 'testemail@email.com'
  }
}));
Aniruddha Das
  • 20,520
  • 23
  • 96
  • 132

1 Answers1

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);
});
Fateh Mohamed
  • 20,445
  • 5
  • 43
  • 52
Anuradha Gunasekara
  • 6,553
  • 2
  • 27
  • 37
  • 2
    you can override only the property you need and keep the service by using: class MockConfigService extends ConfigService { ..} – Fateh Mohamed Jun 20 '18 at 12:10