I want to create test for my component. I have router resolver that resolve data and read data in ng init .i want create test for that .How can i create test for this code
@Component({
selector: 'jhi-label-detail',
templateUrl: './label-detail.component.html'
})
export class LabelDetailComponent implements OnInit {
label: Label;
constructor(
private route: ActivatedRoute
) {
}
ngOnInit() {
this.route.data.subscribe(({label}) => {
this.label = label.body ? label.body : label;
});
}
}
and route is like this
{
path: 'label/:id/view',
component: LabelDetailComponent,
resolve: {
label: LabelResolve
}
}
and resolve is this
@Injectable()
export class LabelResolve implements Resolve<any> {
constructor(private service: LabelService) {
}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const id = route.params['id'] ? route.params['id'] : null;
if (id) {
return this.service.find(id);
}
return new Label();
}
}
Test Cases for ActivatedRoute it('getDataByNameAndID test case ', () => {route.snapshot.params.id = '2';route.snapshot.params.name = 'testParamChanged';fixture = TestBed. createComponent(MyComponent);component = fixture. componentInstance;fixture. detectChanges();expect(component.name).
Router does redirecting, don't call APIs about "getting the route information". If you needed to subscribe to changes in route, use this. router . ActivatedRoute does all "get the query params, get current URL, etc".
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.
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { ActivatedRoute } from '@angular/router';
import { of } from 'rxjs/observable/of';
import { Observable } from 'rxjs/Observable';
import { MyComponent } from './my-component.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture<MyComponent>;
const route = ({ data: of({ label: 'hello' }) } as any) as ActivatedRoute;
beforeEach(
async(() => {
TestBed.configureTestingModule({
declarations: [MyComponent],
providers: [{ provide: ActivatedRoute, useValue: route }],
}).compileComponents();
}),
);
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should set the label', () => {
expect(component.label).toEqual('hello');
});
});
The important thing to note here is that we are providing our own implementation of ActivatedRoute
in TestBed.providers
, with just one property (data
) that is being used by our component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With