Reputation: 38713
I want to know how to mock ActivatedRoute url.
I am getting current url by using ActivatedRoute
this.activatedRoute.url.subscribe(url => {
this.isEdit = false;
if (url[0].path === 'updatecoc') {
this.isEdit = true;
}
});
So I want to mock url in ActivatedRoute
I have tried this
let fakeActivatedRoute = new MockActivatedRoute();// MockActivatedRoute I have implemented this class from MockActivatedRoute class
fakeActivatedRoute.parent = new MockActivatedRoute();
let urlSegment: UrlSegment[] = [];
urlSegment.push({ path: "updatecoc", parameters: {} });
fakeActivatedRoute.url = Observable.of(urlSegment);
TestBed.configureTestingModule({ { provide: ActivatedRoute, useValue: fakeActivatedRoute }})
But I am getting error:
unable to get property 'subscribe' of undefined or null reference
I don't know where I am missed. How can I resolve this issue?
Upvotes: 0
Views: 828
Reputation:
I have a better solution for you :
import { RouterTestingModule } from '@angular/router/testing';
TestBed.configureTestingModule({
imports: [RouterTestingModule],
// ...
})
.compileComponents();
This will mock your whole routing module, now you can inject your dummy mock into your providers and spy on the functions like so
providers: [{provide: ActivatedRoute, useValue: {}}]
And when you test a function calling, let's say, myMock
(I know it's not in it, it's for the example) :
const mock = TestBed.get(ActivatedRoute);
spyOn(mock, 'myMock').and.returnValue(/* what you want */);
// ...
expect(mock.myMock).toHaveBeenCalledWith(/* params here */);
EDIT I quickly looked at what url is made of, here is your mock :
mock.url = jasmine
.createSpy()
.and
.returnValue(new BehaviorSubject({
path: 'yout-mocked-path',
parameters: {/* your mocked parameters */}
})));
Upvotes: 1