Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Unit Test Angular 2 routing params

Say that I want to simply unit test a component that takes parameters taken from a part of the route. For instance, my component's ngOnInit looks like this:

  ngOnInit() {
    this.route.parent.params.switchMap((params: Params) => this.service.getProject(params['projectId']))
      .subscribe((project: Project) => this.update(project));
  }

How can I now: 1: setup my test so that the component create works at all, so I can unit test other parts

Edited with answer - the example ActivatedRouteStub should be extended with a parent that also has an observable params, and I should have used useClass instead of useValue (forgot to change that back):

@Injectable()
export class ActivatedRouteStub {

    // ActivatedRoute.params is Observable
    private subject = new BehaviorSubject(this.testParams);
    params = this.subject.asObservable();

    // Test parameters
    private _testParams: {};
    get testParams() { return this._testParams; }
    set testParams(params: {}) {
        this._testParams = params;
        this.subject.next(params);
    }

    // ActivatedRoute.snapshot.params
    get snapshot() {
        return { params: this.testParams };
    }
        // ActivatedRoute.parent.params
    get parent() {
        return { params: this.subject.asObservable() };
    }
}

2: provide a value for projectId in my UnitTest?

The examples from the angular2 documentation do not seem to work for switchMap, or even at all (I've used the ActivatedRouteStub from there, but no luck with that so far - params is always undefined).

Edited with answer:

describe('ProjectDetailsComponent', () => {
  let component: ProjectDetailsComponent;
  let fixture: ComponentFixture<ProjectDetailsComponent>;
  let activatedRoute: ActivatedRouteStub;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule.withRoutes([{ path: 'projects/:projectId', component: ProjectDetailsComponent }])],
      declarations: [ProjectDetailsComponent],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [{ provide: ProjectsService, useClass: ProjectsServiceStub }, {provide: ActivatedRoute, useClass: ActivatedRouteStub}]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ProjectDetailsComponent);
    component = fixture.componentInstance;
    activatedRoute = fixture.debugElement.injector.get(ActivatedRoute);
    activatedRoute.testParams = { projectId: '123'};
    fixture.detectChanges();
  });

  fit('should create', () => {
    expect(component).toBeTruthy();
  });
});
like image 892
Arwin Avatar asked Feb 05 '17 12:02

Arwin


People also ask

How do I test my router navigate in Angular jest?

router = TestBed. get(Router); Then, in the testcase, it('should show news intially ', () => { const navigateSpy = spyOn(router,'navigate'); component.

How do I test a router navigate in Angular 8?

We can test routing in Angular by using RouterTestingModule instead of RouterModule to provide our routes. This uses a spy implementation of Location which doesn't trigger a request for a new URL but does let us know the target URL which we can use in our test specs.


2 Answers

The only way params would be undefined is if you're not creating the stub correctly. Look at the call

this.route.parent.params.switchMap

params is a nested property two levels deep. So as plain JS object you would need

let mock = {
  parent: {
    params: Observable.of(...)
  }
}

If you want to use a classes, you could use something like

class ActivatedRouteStub {

  parent = {
    params: Observable.of({})
  };

  set testParams(params: any) {
    this.parent.params = Observable.of(params);
  }
}

You just use a setter on the testParams to set the value of the parent.params. So then when you do stub.testParams = whatever, the value will be set on the observable of the parent.params.

UPDATE

Aside from the above explanation on how you can implement this, you also have an error in your configuration

{provide: ActivatedRoute, useValue: ActivatedRouteStub}

useValue is supposed to be an object that you create. So you are passing a class, and that class will be what is injected, not an instance of the class. If you want Angular to create it, then you should use useClass. Otherwise you should create the instance yourself, and use that instance as the value

{provide: ActivatedRoute, useValue: new ActivatedRouteStub() }

Notice the instantiation.

like image 52
Paul Samsotha Avatar answered Sep 22 '22 11:09

Paul Samsotha


If anybody ends up having this problem with Angular 7, the Angular docs give a clear example how to test components dependent on the ActivatedRoute service. See: https://v7.angular.io/guide/testing#activatedroutestub. Just a bit different from the responses above.

like image 20
Marius Lazar Avatar answered Sep 21 '22 11:09

Marius Lazar