How to test for document being undefined with RTL? - reactjs

I have the following react hook which brings focus to a given ref and on unmount returns the focus to the previously focused element.
export default function useFocusOnElement(elementRef: React.RefObject<HTMLHeadingElement>) {
const documentExists = typeof document !== 'undefined';
const [previouslyFocusedEl] = useState(documentExists && (document.activeElement as HTMLElement));
useEffect(() => {
if (documentExists) {
elementRef.current?.focus();
}
return () => {
if (previouslyFocusedEl) {
previouslyFocusedEl?.focus();
}
};
}, []);
}
Here is the test I wrote for it.
/**
* #jest-environment jsdom
*/
describe('useFocusOnElement', () => {
let ref: React.RefObject<HTMLDivElement>;
let focusMock: jest.SpyInstance;
beforeEach(() => {
ref = { current: document.createElement('div') } as React.RefObject<HTMLDivElement>;
focusMock = jest.spyOn(ref.current as HTMLDivElement, 'focus');
});
it('will call focus on passed ref after mount ', () => {
expect(focusMock).not.toHaveBeenCalled();
renderHook(() => useFocusOnElement(ref));
expect(focusMock).toHaveBeenCalled();
});
});
I would like to also test for the case where document is undefined as we also do SSR. In the hook I am checking for the existence of document and I would like to test for both cases.
JSDOM included document so I feel I'd need to remove it and some how catch an error in my test?

First of all, to simulate document as undefined, you should mock it like:
jest
.spyOn(global as any, 'document', 'get')
.mockImplementationOnce(() => undefined);
But to this work in your test, you will need to set spyOn inside renderHook because looks like it also makes use of document internally, and if you set spyOn before it, you will get an error.
Working test example:
it('will NOT call focus on passed ref after mount', () => {
expect(focusMock).not.toHaveBeenCalled();
renderHook(() => {
jest
.spyOn(global as any, 'document', 'get')
.mockImplementationOnce(() => undefined);
useFocusOnElement(ref);
});
expect(focusMock).not.toHaveBeenCalled();
});

You should be able to do this by creating a second test file with a node environment:
/**
* #jest-environment node
*/
describe('useFocusOnElement server-side', () => {
...
});

I ended up using wrapWithGlobal and wrapWithOverride from https://github.com/airbnb/jest-wrap.
describe('useFocusOnElement', () => {
let ref: React.RefObject<HTMLDivElement>;
let focusMock: jest.SpyInstance;
let activeElMock: unknown;
let activeEl: HTMLDivElement;
beforeEach(() => {
const { window } = new JSDOM();
global.document = window.document;
activeEl = document.createElement('div');
ref = { current: document.createElement('div') };
focusMock = jest.spyOn(ref.current as HTMLDivElement, 'focus');
activeElMock = jest.spyOn(activeEl, 'focus');
});
wrapWithOverride(
() => document,
'activeElement',
() => activeEl,
);
describe('when document present', () => {
it('will focus on passed ref after mount and will focus on previously active element on unmount', () => {
const hook = renderHook(() => useFocusOnElement(ref));
expect(focusMock).toHaveBeenCalled();
hook.unmount();
expect(activeElMock).toHaveBeenCalled();
});
});
describe('when no document present', () => {
wrapWithGlobal('document', () => undefined);
it('will not call focus on passed ref after mount nor on previously active element on unmount', () => {
const hook = renderHook(() => useFocusOnElement(ref));
expect(focusMock).not.toHaveBeenCalled();
hook.unmount();
expect(activeElMock).not.toHaveBeenCalled();
});
});
});

Related

Why is Enzyme document.activeElement an empty object?

I am emplying an useRef to fix focus to button next to input when change of that input is detected:
const handleUserEshopChange = (eshopId: ID) => {
setEshopIdValue(eshopId)
setEshopNameValue('')
focusRef.current.focus()
...
}
I want to test that the focus has been affixed but document.activeElement is just an empty object:
test('onNewEshopCreate is handled correctly', () => {
const mockOnUserEshopSelect = jest.fn()
const mockOnNewEshopCreate = jest.fn()
const useRefSpy = jest.spyOn(React, 'useRef').mockReturnValueOnce({ current: { focus } })
const eshopStep = mount(
<EshopStep
...
/>
, { attachTo: document.body })
act(() => {
eshopStep.find('ForwardRef(AutocompleteInput)').simulate('change', '...')
eshopStep.find('ForwardRef(ContinueButton)').at(1).simulate('click')
})
expect(mockOnNewEshopCreate).toBeCalledTimes(1)
expect(mockOnNewEshopCreate).toBeCalledWith('...')
expect(mockOnUserEshopSelect).toBeCalledTimes(0)
expect(document.activeElement).toBe(eshopStep.find('.button'))
})
Test fails on the last line, as it expects only an ampty object ( {} ). Why is the activeElement empty?

How to spy only one react hook useState

I want to isolate the test to a targeted useState.
Lets say I have 3 useStates, of which some are in my component and some are in children components in this testcase.
Currently this logs for 3 different useStates. How to target the one I want. Lets say its called setMovies.
const createMockUseState = <T extends {}>() => {
type TSetState = Dispatch<SetStateAction<T>>;
const setState: TSetState = jest.fn((prop) => {
// if setMovies ???
console.log('jest - spy mock = ', prop);
});
type TmockUseState = (prop: T) => [T, TSetState];
const mockUseState: TmockUseState = (prop) => [prop, setState];
const spyUseState = jest.spyOn(React, 'useState') as jest.SpyInstance<[T, TSetState]>;
spyUseState.mockImplementation(mockUseState);
};
interface Props {
propertyToTest: boolean
};
describe('Search Movies', () => {
describe('Onload - do first search()', () => {
beforeAll(async () => {
createMockUseState<PROPS>();
wrapper = mount(
<ProviderMovies>
<SearchMovies />
</ProviderMovies>
);
await new Promise((resolve) => setImmediate(resolve));
await act(
() =>
new Promise<void>((resolve) => {
resolve();
})
);
});
});
});
as we know react hooks depends on each initialization position. And for example if you have 3 hooks inside your component and you want to mock the 2-nd, you should mock 1 and 2 with necessary data.
Something like this
//mock for test file
jest.mock(useState); // you should mock here useState from React
//mocks for each it block
const useMockHook = jest.fn(...);
jest.spyOn(React, 'useState').mockReturnValueOnce(useMockHook);
expect(useMockHook).toHaveBeenCalled();
// after that you can check whatever you need

Functions in a jest test only work when launched alone, but not at the same time

I have a custom hook that updates a state. The state is made with immer thanks to useImmer().
I have written the tests with Jest & "testing-library" - which allows to test hooks -.
All the functions work when launched alone. But when I launch them all in the same time, only the first one succeed. How so?
Here is the hook: (simplified for the sake of clarity):
export default function useSettingsModaleEditor(draftPage) {
const [settings, setSettings] = useImmer(draftPage);
const enablePeriodSelector = (enable: boolean) => {
return setSettings((draftSettings) => {
draftSettings.periodSelector = enable;
});
};
const enableDynamicFilter = (enable: boolean) => {
return setSettings((draftSettings) => {
draftSettings.filters.dynamic = enable;
});
};
const resetState = () => {
return setSettings((draftSettings) => {
draftSettings.filters.dynamic = draftPage.filters.dynamic;
draftSettings.periodSelector = draftPage.periodSelector;
draftSettings.filters.static = draftPage.filters.static;
});
};
return {
settings,
enablePeriodSelector,
enableDynamicFilter,
resetState,
};
}
And the test:
describe("enablePeriodSelector", () => {
const { result } = useHook(() => useSettingsModaleEditor(page));
it("switches period selector", () => {
act(() => result.current.enablePeriodSelector(true));
expect(result.current.settings.periodSelector).toBeTruthy();
act(() => result.current.enablePeriodSelector(false));
expect(result.current.settings.periodSelector).toBeFalsy();
});
});
describe("enableDynamicFilter", () => {
const { result } = useHook(() => useSettingsModaleEditor(page));
it("switches dynamic filter selector", () => {
act(() => result.current.enableDynamicFilter(true));
expect(result.current.settings.filters.dynamic).toBeTruthy();
act(() => result.current.enableDynamicFilter(false));
expect(result.current.settings.filters.dynamic).toBeFalsy();
});
});
describe("resetState", () => {
const { result } = useHook(() => useSettingsModaleEditor(page));
it("switches dynamic filter selector", () => {
act(() => result.current.enableDynamicFilter(true));
act(() => result.current.enablePeriodSelector(true));
act(() => result.current.addShortcut(Facet.Focuses));
act(() => result.current.resetState());
expect(result.current.settings.periodSelector).toBeFalsy();
expect(result.current.settings.filters.dynamic).toBeFalsy();
expect(result.current.settings.filters.static).toEqual([]);
});
});
All functions works in real life. How to fix this? Thanks!
use beforeEach and reset all mocks(functions has stale closure data) or make common logic to test differently and use that logic to test specific cases.
The answer was: useHook is called before "it". It must be called below.

Jest mocking a function with hooks fails

I'm using nextJs and jest enzyme for testing of component. I have a component file like below, where I get items array from props and loop to it calling setRef inside useEffect.
[itemRefs, setItemRefs] = React.useState([]);
setRef = () => {
const refArr = [];
items.forEach(item => {
const setItemRef = RefItem => {
refArr.push(RefItem)
}
if(item && item.rendItem){
item.rendItem = item.rendItem.bind(null, setItemRef);
}
}
setItemRefs(refArr);
}
React.useEffect(() => {
setRef();
},[])
My test file is like below :
const items = [
{
original: 'mock-picture-link',
thumbnail: 'mock-thumb-link',
renderItem: jest.fn().mockReturnValue({ props: { children: {} } })
}
];
beforeEach(() => {
setItemRefs = jest.fn(),
jest.spyOn(React, 'useEffect').mockImplementationOnce(fn => fn());
})
it('mocks item references', ()=>{
jest.spyOn(React, 'useState').mockImplementationOnce(() => [items, setItemRefs]);
wrapper = shallow(<Component />).dive();
expect(setItemRefs).toHaveBeenCalledWith(items);
})
The test case fails with expected as items array BUT received a blank array. The console.log inside if(item && item.rendItem) works but console.log inside const setItemRef = RefItem => {... doesn't work I doubt the .bind is not getting mocked in jest.
Any help would be fine.

Mocking component methods with jest

Say I have the following component:
export class ExampleComponent extends Component {
exampleMethod1 = () => {
console.log('in example 1')
}
exampleMethod2 = () => {
console.log('in example 2')
this.exampleMethod1()
}
render() {
return (
<TouchableOpacity id='touchable' onPress={exampleMethod2}><Text>Touchable</Text></TouchableOpacity>
)
}
}
This works exactly how you would expect. The button appears, and can be pressed. Both methods fire, and console log their text.
I now try to test this with jest:
describe('example tests', () => {
let wrapper
beforeEach(() => {
wrapper = shallow(<ExampleComponent/>)
})
it('this test fails. Interestingly both messages still print', () => {
const instance = wrapper.instance()
instance.exampleMethod2 = jest.fn()
wrapper.find('#touchable').simulate('press')
//wrapper.update() uncommenting this line has no effect.
expect(instance.exampleMethod2.mock.calls.length).toBe(1)
})
it('this test passes. Only the first message prints', () => {
const instance = wrapper.instnace()
instance.exampleMethod1 = jest.fn()
wrapper.find('#touchable').simulate('press')
expect(instance.exampleMethod1.mock.calls.length).toBe(1)
})
})
As annotated, the first test fails, and the original message prints, as if I had never mocked out the method. This happens irrespectively of whether wrapper.update() is run or not.
Interestingly, if we replace the onPress with a seemingly identical arrow function like so:
onPress={() => {exampleMethod2()}}
The test suddenly passes. This whole thing suggest some weird this binding shenanigans (I think?). Any explanation as to what is going on would be much appreciated!
If you want to test custom methods on component's prototype object, you should use mount function from enzyme and use spyOn to mock and trace the call to that method.
export class ExampleComponent extends Component {
exampleMethod1 = () => {
console.log('in example 1');
this.setState({ example1: true });
}
exampleMethod2 = () => {
console.log('in example 2')
this.exampleMethod1()
}
render() {
return (
<TouchableOpacity id='touchable' onPress={exampleMethod2}><Text>Touchable</Text></TouchableOpacity>
)
}
}
describe('example tests', () => {
let wrapper
beforeEach(() => {
wrapper = mount(<ExampleComponent/>)
})
afterAll(() => { wrapper = null; })
it('some desc here', () => {
const instance = wrapper.instance();
spyOn(instance, 'exampleMethod1').and.callThrough();
expect(instance.setState).toHaveBeenCalled();
});
})

Resources