首页 > 解决方案 > 如何使用 Jest 测试 window.location 的路径名

问题描述

我有一个按钮,当点击一个阿波罗突变的火灾时,如果它可以进行导航。我想测试导航是否在我期望的地方

test('I click the Bekraeft button', async () => {
        global.window.location = {
    ...window.location, pathname: '/tilkoeb/1268' };
        const element = await waitFor(() => screen.getByTestId('CurrentSubscriptionOverview'));
        expect(element);
       // getbyText not working with danish characters evidently
      const newbutton = element.querySelector('button[type="submit"]');
      expect(newbutton);
      if (newbutton) {
         fireEvent.click(newbutton);
      }
      await waitFor(() => { expect(global.window.location.pathname).toEqual('/tilkoeb/1268/kvittering'); })
        
      });

if(newbutton)行用于安抚打字稿。

一切正常,直到我添加该行

expect(global.window.location.pathname).toEqual('/tilkoeb/1268/kvittering');

消息失败

expect(received).toEqual(expected) // deep equality
Expected: "/tilkoeb/1268/kvittering"
Received: "/"

我有这样的感觉——从我正在阅读的所有答案和教程中,似乎经历了各种循环来模拟导航,我们只是无法获得实际的导航或无法实现?

但是,如果我可以做到这一点,我如何查看单击按钮时导航到的位置?

标签: jestjsreact-testing-library

解决方案


推荐阅读