Javascript Can';t侦听测试组件中的哈希更改事件
我有一个函数React组件,它侦听哈希更改并相应地调用函数:Javascript Can';t侦听测试组件中的哈希更改事件,javascript,reactjs,typescript,jestjs,enzyme,Javascript,Reactjs,Typescript,Jestjs,Enzyme,我有一个函数React组件,它侦听哈希更改并相应地调用函数: const Component: React.FC = () => { function handleHashChanged() { } useEffect(() => { window.addEventListener('hashchange', handleHashChanged); return () => window.remove
const Component: React.FC = () => {
function handleHashChanged() {
}
useEffect(() => {
window.addEventListener('hashchange', handleHashChanged);
return () => window.removeEventListener('hashchange', handleHashChanged);
});
};
这在正常情况下工作良好,但在运行测试(使用酶)时不起作用。在测试中,我将组件安装在文档上,如下所示,但运气不佳:
const component = mount(<Component/>, { attachTo: document.body });
window.location.hash = "test";
// handleHashChange not called
const component=mount(,{attachTo:document.body});
window.location.hash=“测试”;
//未调用handleHashChange
您可以使用来分派
例如
index.tsx
:
import React, { useEffect } from 'react';
export const Component: React.FC = () => {
function handleHashChanged(event) {
console.log(event.newURL);
}
useEffect(() => {
window.addEventListener('hashchange', handleHashChanged);
return () => window.removeEventListener('hashchange', handleHashChanged);
});
return <div>a component</div>;
};
import { mount } from 'enzyme';
import React from 'react';
import { Component } from './';
describe('67051487', () => {
it('should pass', () => {
const addEventListenerSpy = jest.spyOn(window, 'addEventListener');
const removeEventListenerSpy = jest.spyOn(window, 'removeEventListener');
const component = mount(<Component />);
expect(addEventListenerSpy).toBeCalledWith('hashchange', expect.any(Function));
window.dispatchEvent(
new HashChangeEvent('hashchange', {
oldURL: 'http://example.com/index.html#123',
newURL: 'http://example.com/idnex.html#456',
})
);
component.unmount();
expect(removeEventListenerSpy).toBeCalledWith('hashchange', expect.any(Function));
addEventListenerSpy.mockRestore();
removeEventListenerSpy.mockRestore();
});
});
测试结果:
PASS examples/67051487/index.test.tsx (8.696 s)
67051487
✓ should pass (53 ms)
console.log
http://example.com/idnex.html#456
at handleHashChanged (examples/67051487/index.tsx:5:13)
-----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
index.tsx | 100 | 100 | 100 | 100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 9.633 s
软件包版本:
“酶”:“^3.11.0”,
“笑话”:“^26.6.3”,
“反应”:“^16.14.0”,