Home > Back-end >  Testing URL Params in Angular Unit Test
Testing URL Params in Angular Unit Test

Time:03-16

I am attempting to test for a string contained within URL parameters. In my typescript file I have the method:

 checkURLParams() {
    if (this.route.parent) {
      this.route.parent.params.subscribe((params) => {
        if (params['view'] === 'view') {
          this.form.disable();
        }
      });
    }
  }

The test should ensure that when the parameters contain the string 'view', the form should be disabled.

Currently in my spec file I have:

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [MyComponent],
      imports: [
        RouterTestingModule,
        ReactiveFormsModule
      ],
   
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    component.ngOnInit();
    fixture.detectChanges();
  });

  fit('test', fakeAsync(() => {

    // Arrange


    // Act
    component.checkURLParams();


    // Assert
    expect(component.form.disabled).toBeTruthy();
  }));

I have seen some solutions to different ways of testing URL parameters but cannot find a way to mock the URL parameters in the test to contain 'view' in order to disable the form. What would be the best approach to solving this?

CodePudding user response:

I had similar case where i needed test URLs and results.


  let fixture: ComponentFixture<AppComponent>;
  let component: AppComponent;
  let location: Location;
  let router: Router;

  beforeEach(() => {
    location = TestBed.inject(Location);
    fixture = TestBed.createComponent(AppComponent);
    component = fixture.debugElement.componentInstance;
    router = TestBed.inject(Router);

    fixture.ngZone.run(() => {
      router.initialNavigation();
    });
  });

  it('test', waitForAsync(() => {
      fixture.ngZone.run(async () => {
        await router.navigate(['yourUrl/With/Params']);
        fixture.detectChanges();
        component.checkURLParams();
        expect(component.form.disabled).toBeTruthy();
      });
    })
  );
  • Related