go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/milo/ui/src/testing_tools/url_observer.tsx (about)

     1  // Copyright 2024 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  import { useLocation } from 'react-router-dom';
    16  
    17  export const locationCallback = jest.fn((_path: string) => {});
    18  
    19  export interface Location {
    20    readonly pathname: string;
    21    readonly search: { [key: string]: string };
    22    readonly hash: string;
    23  }
    24  
    25  export interface URLObserverProps {
    26    /**
    27     * Called when the component is rerendered. Useful to get the location in a
    28     * structured format. When you pass in a `const mockedCallback = jest.fn()`,
    29     * the location can be tested with
    30     * ```
    31     * expect(urlCallback).toHaveBeenLastCalledWith(
    32     *   expect.objectContaining({
    33     *     pathname: ...,
    34     *     search: {
    35     *       key1: ...,
    36     *       ...,
    37     *     },
    38     *     hash: ...,
    39     *   }),
    40     * );
    41     * ```
    42     */
    43    readonly callback?: (location: Location) => void;
    44  }
    45  
    46  /**
    47   * A simple component that renders the URL to a span with data-testid="url".
    48   * This is useful for testing against URLs.
    49   */
    50  export function URLObserver({ callback = () => {} }: URLObserverProps) {
    51    const location = useLocation();
    52    callback({
    53      pathname: location.pathname,
    54      hash: location.hash,
    55      search: Object.fromEntries(new URLSearchParams(location.search).entries()),
    56    });
    57    return (
    58      <span data-testid="url">
    59        {location.pathname + location.search + location.hash}
    60      </span>
    61    );
    62  }