【问题标题】:Mocking window.get() with Jest用 Jest 模拟 window.get()
【发布时间】:2021-04-10 16:41:59
【问题描述】:

如下所示的 TypeScript 类访问 window 全局:

class WindowEnv {
  get(varName: string): string {
    return (window as any)._env_[varName];
  }
}

这个类被一个名为Headlines 的 React 组件间接访问。我试图通过模拟存储在window 全局中的值来测试这个组件。这是我的测试:

// Set API_URL in window environment
(window as any)._env_ = {
  API_URL: 'http://localhost:8080',
};

describe('<Headlines />', () => {
  test('renders correctly', async () => {
    const { findByTestId, findByText } = render(<Headlines />);
    expect(await findByText('Headlines')).toBeTruthy();

    // expect 4 headlines
    const headlineList = await findByTestId('headline-list');
    const headlines = headlineList.querySelectorAll('tbody tr');
    expect(headlines.length).toBe(4);
  });
});

但是测试中断说它找不到全局窗口:

TypeError: Cannot read property 'API_URL' of undefined

模拟window 全局的最佳方法是什么?

【问题讨论】:

  • 这个类被一个名为 Headlines 的 React 组件间接访问 - 在哪里?该问题不包含导致问题的代码。尚不清楚window 是否未定义。 _env_[varName] 在一个地方,_env_.API_URL 在另一个地方(一个点)。

标签: reactjs typescript jestjs


【解决方案1】:

在 describe 测试块中,您可以为 window 对象编写 mock 并为其设置环境值

  describe('<Headlines />', () => {
      const envValue = {
        API_URL: 'http://localhost:8080',
      };
    
      Object.defineProperty(window, '_env_', { value: envValue })
  
      test('renders correctly', async () => {
       //test logic of component
       ....
      });
    });

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 2020-04-21
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-04
    • 2019-08-17
    • 2023-04-02
    相关资源
    最近更新 更多