【问题标题】:How to check if else conditions containing window.location.href (React Component) using Jest如何使用 Jest 检查是否包含 window.location.href(React 组件)的其他条件
【发布时间】:2021-10-18 23:20:50
【问题描述】:

我刚开始使用带有 .spec.js 后缀的文件来测试带有 Jest 的文件,所以希望这不是一个愚蠢的问题。我没有通过 Google + Stackoverflow 研究发现任何东西。

我想使用 jest 检查包含新 window.location 的 if else 条件。

这是我的文件.ts

export const loadBSection = (bSectionId: string) => async (
  dispatch: Dispatch,
  getState: GetState,
  { bSectionApi }: Deps,
) => {
  try {
    ...
  } catch (e) {
    dispatch(setBSectionErrorMessage(e.message));
    if (e.response.status === 404) {
      window.location.href = '/page-not-found.html';
    }
  }
};

我的文件.spec.ts

it('should .. and forward to a 404 page', async () => {
    ...
    expect(store.getActions()).toEqual([setBSectionLoading(true), setBSectionErrorMessage(errorMessage)]);

    // TODO what is expected here?
    
  });

你有什么想法吗?

由于我是新手,也许您有一些深入研究的资源?

我使用:https://create-react-app.dev/docs/running-tests/ 作为介绍。 您是否还有其他资源可以帮助您将来找到一些文档?

【问题讨论】:

    标签: reactjs typescript unit-testing jestjs ts-jest


    【解决方案1】:

    我有一个想法,但不确定它是否有效

    Object.defineProperty(window.location, 'href', {
      writable: true,
      value: '/page-not-found.html',
    });
    

    【讨论】:

    • mmh.. 试过了,还是不行。猜猜添加它是强制性的(如果状态为 404)很重要
    【解决方案2】:

    解决了!

    因此,将response 设置为可选是很有用的,这样其他错误也会被捕获。此外,模拟函数更容易,所以我将window.location.href 更改为window.location.assign(url)。 相同但更易于测试。

    file.ts

    catch (e) {
        dispatch(setBSectionErrorMessage(e.message));
        if (e.response?.status === 404) {
          window.location.assign('/page-not-found.html');
        }
      }
    

    file.spec.ts

    我正在测试方法中创建errorerrorMessage。在这里,您可以看到如何将错误对象与状态代码组合起来作为响应:

    it('should navigate to /page-not-found.html ...', async () => {
        const bSectionIdMock = '123';
        const error = Object.assign((new Error(), { response: { status: 404 } }));
        bSectionApi.bSectionsBSectionIdGet.mockRejectedValue(error);
    
        window.location.assign = jest.fn();
    
        await store.dispatch(loadBSection(bSectionIdMock));
    
        expect(window.location.assign).toHaveBeenCalledWith('/page-not-found.html');
      });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      • 2017-07-09
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多