angularjasmineangular-activatedroute

Dynamically change query params Angular unit test


I have a component that has 2 different states dependent on the query params provided. Here's the 2 query param states:

  const mockLocalQueryParams = {
    Id: Guid.create(),
    customerId: Guid.create(),
  };

  const mockOrganicQueryParams = {
    id1: Guid.create(),
    id2: Guid.create(),
    id3: 1,
    id4: 2,
  };

I'm using mockLocalQueryParams as the default state but I want to change to mockOrganicQueryParams so I can test functionality for that state also

beforeEach(
  waitForAsync(() => {
    TestBed.configureTestingModule({
      providers: [
        {
          provide: ActivatedRoute,
          useValue: {
            queryParams: of(mockLocalQueryParams),
          },
        },
      ],
    }).compileComponents();
  })
);

I've tried creating a new describe block and TestBed.inject(ActivatedRoute).snapshot.params = of(mockOrganicQueryParams) and other similar things but this undefined.

How can I change the query params for when I want to test mockOrganicQueryParams state?


Solution

  • The best way in my opinion is to do it through a BehaviorSubject that you can have a handle on. Something like this:

    // !! create a behavior subject here so you can have a handle on it
    const mockQueryParams = new BehaviorSubject<any>(mockLocalQueryParams);
    beforeEach(
      waitForAsync(() => {
        TestBed.configureTestingModule({
          providers: [
            {
              provide: ActivatedRoute,
              useValue: {
               // !! assign the query params as an observable here
                queryParams: mockQueryParams.asObservable(),
              },
            },
          ],
        }).compileComponents();
      })
    );
    

    Whenever you want to change the queryParams subscription, you can just do mockQueryParams.next(mockOrganicQueryParams);