0

I have a service like

export class TestService {
  public props: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  props$ = this.props.asObservable();

  test(){
  
}

}

and this is my .spect file of my component

 let component: MainComponent;
  let fixture: ComponentFixture<MainComponent>;
  let testServiceSpy: jasmine.SpyObj<TestService>;

  beforeEach(async(() => {
    testServiceSpy = jasmine.createSpyObj<TestService>("TestService", [
      "test",
    ],);
    TestBed.configureTestingModule({
      declarations: [ MainComponent ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      imports:[HttpClientTestingModule],
      providers:[
        {
          provide:TestService,
          useValue:technicalFacilitiesServiceSpy,
          },
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(MainComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

and when I try to test in my .spect file like

  testServiceSpy.props

I see undefined, how could I get the default value? false in this case

1 Answers1

0

You have to use the 3rd argument of createSpyObj to mock the public instance variable.

Try doing the following:

testServiceSpy = jasmine.createSpyObj<TestService>("TestService", [
      "test",
    ], { props$: of(false) });
....
{
   provide: TestService,
   useValue: testServiceSpy
}

Check out this link on how to change the instance variable: https://stackoverflow.com/a/43793575/7365461

AliF50
  • 16,947
  • 1
  • 21
  • 37