Stub ActivatedRoute in Angular 2 tests

I'm struggling to figure out how to disable the activated angular route for my purposes. In one of my components, I use a route snapshot to get a portion of the activated route URL:

let activatedPath = this.route.snapshot.children[0].url[0].path;

In my tests, I get an error message:

Error: Error in :0:0 caused by: undefined is not an object (evaluating 'this.route.snapshot.children[0].url')โ€‹โ€‹

So, I believe that I need to drown out the Activated route:

class FakeActivatedRoute {
    // stub detail goes here
}

and indicate this in my test:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [
        SiteAdminComponent
      ],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        { provide: ActivatedRoute, useClass: FakeActivatedRoute }
      ]
    })
     .compileComponents();
}));

Can anyone suggest any guidance on implementing a stub that would allow me to get to .snapshot.children[0].url[0].path? Currently, I am not getting anywhere :-)

+4
source share
1 answer

You should be able to do something like:

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [
        SiteAdminComponent
      ],
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        { 
          provide: ActivatedRoute, 
          useValue: {snapshot: {children: [{url: ['your/path/here']}]}} 
        }
      ]
    })
     .compileComponents();
}));

Route, .

+2

Source: https://habr.com/ru/post/1662980/


All Articles