1

My Angular component depends uses an activatedRoute that has a data parameter set using a resolver service. For my unit tests, I like to mock this out, like this:

activatedRouteStub = { data: { subscribe: (fn: (value: Data) => void) => fn({ someObject: SomeObjectMock // hard coded JSON value }), } }; TestBed.configureTestingModule({ declarations: [SomeComponent], providers: [ { provide: ActivatedRoute, useValue: activatedRouteStub } ] }); route = fixture.debugElement.injector.get(ActivatedRoute);// where route is in an instance of ActivatedRoute that is injected into SomeComponent as a dependency

This works fine for the initial set of tests that depend on this behavior of activatedRoute. But now, I need to change what is actually returned, basically, I need to use a modified SomeObjectMock and set it to someObject.

And I am short of ideas on how to do it, I have tried doing the following:

route = { data: { subscribe: (fn: (value: Data) => void) => fn({ someObject: SomeObjectMock // hard coded JSON value }), } };

This had previously worked when I was stubbing a simple service, changing the definition of a method to return a different value was fairly trivial.

Any suggestions/pointers?

Parijat Kalia
  • 4,929
  • 10
  • 50
  • 77

1 Answers1

3

It sounds like you would like to change the data returned by ActivatedRoute.data over the course of your test.

I'm assuming that in your component under test you have something like this:

this.route.data.subscribe(data => {
    // do something
})

ActivatedRoute.data is an RxJS Observable so you will want to create an observable to mock this.

You will probably never want to override the subscribe method. Instead, you will probably want to provide the correct data that your subscriber can consume.

I will do something similar to this: Observable vs Subject and asObservable

const myData = new Subject(); // import { Subject } from 'rxjs/Subject'; 

activatedRouteStub = {
     data: myData.asObservable()
    };
     TestBed.configureTestingModule({
      declarations: [SomeComponent],
      providers: [
        { provide: ActivatedRoute, useValue: activatedRouteStub }
      ]
    });
route = fixture.debugElement.injector.get(ActivatedRoute);

Then, you can call myData.next(data) whenever you wish to change the data being returned, like this:

const dataYouWantReturned = {};
myData.next(dataYouWantReturned)

Good luck!

Rosalind
  • 91
  • 1
  • 6