javascript - 在酶中模拟 history.back()
问题描述
对于反应组件测试,我需要模拟浏览器。这可能与已安装的组件有关吗?
我试过的:
it('triggers onpopstate events', () => {
requiredProps.filterBlocks = mockData.filterBlocks;
const wrapper = mount(<FilterBlocks {...requiredProps} />);
global.window.history.pushState({ mock: 'MOCK'}, "mock", "mock.html");
global.window.history.pushState({ mock: 'MOCK2'}, "mock", "mock2.html");
global.window.history.back();
expect(mockedFunction).toHaveBeenCalled();
})
在组件(componentDidMount)内部,我有一个 window.onpopstate 监听器:
window.onpopstate = event => {
console.log('event', event);
};
但是不会将任何内容记录到控制台。
解决方案
对于我的测试,我手动触发了 onpopstate:
const testEvent = { target: "mock" };
global.window.onpopstate(testEvent);