【发布时间】: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