【问题标题】:Can't see that window.location has changed - react testing library看不到 window.location 已更改 - 反应测试库
【发布时间】:2021-09-03 08:11:30
【问题描述】:

我有一个简单的 404 组件,它将更改 window.location 以将“/404”添加到当前位置。

const My404 = () => {
    const location = useLocation();

    useEffect(() => {
        window.location.replace(`/404${location.pathname}`);
    }, []);

    ...

我正在尝试使用 React 测试库对此进行测试,但我似乎无法让它看到变化,即使在使用 await waitFor...

it('Should add /404 to start of pathname', async () => {
        const history = createMemoryHistory()
        history.push('/some-route')
        const rendered = render(
            <Router history={history}>
                <My404 />
            </Router>
        );
        
        await waitFor(() => expect(window.location.pathname).toBe('/404/some-route'));
    });

测试失败:

Expected: "/404/some-route"
Received: "/"

更新 我只是通过在更改前后注销location 和window.location.pathname 进行了快速检查...

位置:

{ location:
   { 
      pathname: '/some-route',
      search: '',
      hash: '',
      key: '14xswz' 
   } 
}

window.location.pathname:

/

【问题讨论】:

  • 我认为你不应该使用window.location.replace,而是使用useHistory 并调用history.replace()。
  • 啊,是的!我知道我错过了一些东西。我确实最终让我的代码正常工作,所以我一定会添加一个封装这两条路线的答案。

标签: reactjs location window react-testing-library pathname


【解决方案1】:

在@Chris 给我建议使用特定于 React 的 useHistory 钩子之前,我设法解决了这个问题。我将概述我修复测试的两种方式。

不使用 useHistory - 老式方式

it('Should add /404 to start of pathname', () => {
    // Create a mock of the window.location.replace function
    const replaceMock = jest.fn();

    // Define the window to use the mocked function above
    Object.defineProperty(window, "location", {
        value: {
            replace: replaceMock,
        },
        writable: true
    });

    const rendered = render(
        <MemoryRouter initialEntries={['/some-route'}>
            <My404 />
        </MemoryRouter>
    );

    // Expect mocked function to be called once with arg
    expect(replaceMock).toHaveBeenCalledTimes(1);
    expect(replaceMock).toHaveBeenLastCalledWith('/404/some-route');
});

使用 useHistory 我重新设计了组件以使用useHistory 钩子,而不是依赖window.location。

useEffect(() => {
    history.replace(`/404${location.pathname}`);
}, []);

然后我更新了测试以反映更改

it('Should add /404 to start of pathname', () => {
    const history = createMemoryHistory({ initialEntries: ['/some-url'] });

    const rendered = render(
        <Router history={history}>
            <My404 />
        </Router>
    );

    expect(history.location.pathname).toBe('/404/some-url');
});

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2019-08-06
    • 2019-03-08
    • 1970-01-01
    • 2020-01-21
    相关资源
    最近更新 更多