简体   繁体   中英

Angular2 Unit Tests - Test Subject ( watch on variable from service)

I have a watch in one of my components which watches a variable in a service (so a Subject). (I got the implementation idea of this here: updating variable changes in components from a service with angular2. However, now my whole tests in the component are failing because I need to mock this somehow but I don't know how and I could not find any answer to that. That's my code:

Component where I watch the change of the variable in the constructor:

  constructor(private updateService: UpdateService) {

    // check if intents are updated in the updateService through upload component, if yes update training status
    this.intentsSubscription = updateService.intentsChange.subscribe((value) => this.initTrainingStatus());
  }

Service where the Variable-Change is triggered:

 public intentsChange: Subject<object> = new Subject<object>();
   .....

    public updateIntents(appId: number) {
        this.requestsService.getAllIntents(appId)
          .subscribe(intents => {
            this.setIntents(intents);
            this.intentsChange.next(intents);
          });
      }

Tests of the component which are currently failing because:

TypeError: updateService.intentsChange.subscribe is not a function

describe('TrainButtonComponent', () => {
  let component: TrainButtonComponent;
  let fixture: ComponentFixture<TrainButtonComponent>;

  let mockUpdateService;
  let intentsChange: Subject<object> = new Subject<object>();


  beforeEach(async(() => {
      intentsChange() {
        return Subject.of({});
      }
    };
    TestBed.configureTestingModule({
      imports: [ ],
      declarations: [ TrainButtonComponent ],
      providers: [
        { provide: UpdateService, useValue: mockUpdateService }
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TrainButtonComponent);
    component = fixture.componentInstance;
    mockUpdateService = fixture.debugElement.injector.get(UpdateService);
    fixture.detectChanges();
  });

  it('should be created', () => {
    expect(component).toBeTruthy();
  });

});

Does anyone know how to fix that Error so my Tests are actually running through again?

intentsChange what you declared in beforeEach do nothing.

All what you need is to correctly mock updateService in before each:

updateService = TestBed.get(UpdateService); // or somehow else, as you wish
spyOn(updateService, 'intentsChange').and.returnValue(Observable.of(<SomeValueHere>)); // <-- here is main point

Now check that this.initTrainingStatus() was called. This will work.

Don't forget to import 'rxjs/add/observable/of' somewhere at the top.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM