Whn going through the docs for react router, I came across a utility component that helps track page changes (for what ever purpose needed). This is the component:
export const PageTracker = (props: PageTrackerProps) => {
const { callback } = props;
let location = useLocation();
React.useEffect(() => {
callback(location);
}, [location, callback]);
return null;
};
I want to add a test to it to make sure that the callback is indeed called on location change, but can't figure it out.
describe("<PageTracker />", () => {
let wrapper;
let history;
test("The callback is called when route changes", () => {
const mockCallback = jest.fn();
wrapper = mount(
<MemoryRouter initialEntries={["/"]}>
<PageTracker callback={mockCallback} />
</MemoryRouter>
);
history = wrapper.instance().history;
expect(mockCallback).toBeCalledTimes(1);
history.push("/new-url");
expect(mockCallback).toBeCalledTimes(2);
});
});
But it fails here: expect(mockCallback).toBeCalledTimes(2);
saying it still was only called once.
I've tried changing the test a bit (just moving things around, not much of a change):
describe("<PageTracker />", () => {
test("The callback is called when route changes", () => {
const mockCallback = jest.fn();
const wrapper = mount(
<MemoryRouter initialEntries={["/"]}>
<PageTracker callback={mockCallback} />
</MemoryRouter>
);
const history = wrapper.instance().history;
expect(mockCallback).toBeCalledTimes(1);
history.push("/new-url");
expect(mockCallback).toBeCalledTimes(2);
});
});
And now I get an rror on this line const history = wrapper.instance().history;
saying const history = wrapper.instance().history;
.
I don't have much experience with jest/enzyme, would appreciate a point in the right direction.
Aucun commentaire:
Enregistrer un commentaire