模拟窗口对象jest中的ontouchstart事件



我试图模拟ontouchstart事件在窗口对象做一些测试,但我找不到一个合适的方法来做到这一点

export const main = () =>
!!('ontouchstart' in window || navigator.maxTouchPoints);

我试着做

it('123', () => {
const spyWindowOpen = jest.spyOn(window, 'ontouchstart');
spyWindowOpen.mockImplementation(jest.fn());
});

但是ontouchstart在我的编译测试中似乎不存在于窗口对象

这样做没关系:

describe('support ontouchstart', () => {
it('return true when window support ontouchstart event', () => {
// eslint-disable-next-line no-global-assign
window = {
ontouchstart: jest.fn(),
};
expect(!!('ontouchstart' in window)).toBe(true);
});
});
})

请务必像下面这样将窗口重置为原始位置

it('should render', () => {
const original = window.ontouchstart;
window.ontouchstart = jest.fn();   
// rest of your code like 
// expect(!!('ontouchstart' in window)).toBe(true);
window.ontouchstart = original;

});

最新更新