下面显示的 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
全局的最佳方法是什么?
答案 0 :(得分:0)
在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
....
});
});