-
Notifications
You must be signed in to change notification settings - Fork 0
ReactJS
alex [dot] kramer [at] g_m_a_i_l [dot] com edited this page Dec 4, 2021
·
8 revisions
Borrowed from: https://stackoverflow.com/a/59843241
import { useEffect, useRef } from "react";
const usePrevious = (value, initialValue) => {
const ref = useRef(initialValue);
useEffect(() => {
ref.current = value;
});
return ref.current;
};
const useEffectDebugger = (effectHook, dependencies, dependencyNames = []) => {
const previousDeps = usePrevious(dependencies, []);
const changedDeps = dependencies.reduce((accum, dependency, index) => {
if (dependency !== previousDeps[index]) {
const keyName = dependencyNames[index] || index;
return {
...accum,
[keyName]: {
before: previousDeps[index],
after: dependency
}
};
}
return accum;
}, {});
if (Object.keys(changedDeps).length) {
console.log('🔥🔥🔥=====> [use-effect-debugger] ', changedDeps);
}
useEffect(effectHook, dependencies);
};
import React from "react";
import { MemoryRouter, useHistory } from 'react-router-dom';
import { render } from "@testing-library/react";
const HistoryTest = ({goto}) => {
const history = useHistory();
history.push(goto);
return <></>
}
const mockHistoryPush = jest.fn();
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
push: mockHistoryPush,
}),
}));
describe('Test mocking useHistory', () => {
it('Redirects to correct URL on click', () => {
render(
<MemoryRouter>
<HistoryTest goto="lol" />
</MemoryRouter>,
);
expect(mockHistoryPush).toHaveBeenCalledWith('lol');
});
});