I have a testing suite, that tests a component that uses a context, I am simply trying to test when user inputs some characters/words in a form, and testing if those changes are reflected in the input, the onChangeEvent is a function that we pull from the context.
BUT when I fireEvent, those changes are not reflected and the test fails.
This is how I am mocking the form,
const renderMockForms = () =>
{
return render(
<ContextProvider>
<FormPage />
</ContextProvider>);
};
And a test that looks like
fit("Test Empty Validation when input value is invalid", async () =>
{
mockUseContext.mockReturnValue({ ...contextValues })
const { container } = renderMockForms();
await act( async () => {
const input = container.querySelector(".inputStyles");
expect(input).not.toBeNull();
console.log(input)
expect(input.value).toBe("");
fireEvent.focus(input as Element);
fireEvent.change(input as Element, { target: { value: '!@#$' } });
fireEvent.blur(input as Element);
expect(input.value).toBe('!@#$')
await new Promise(resolve => setTimeout(resolve, 10));
expect(screen.getByText("Invalid Input")).toBeTruthy();
})
})
we are mocking the context like so,
jest.mock('./Context/Context.tsx', () => ({
...jest.requireActual('./Context/Context.tsx'),
useContext: jest.fn()
}))
const { useContext: mockUseContext } =
jest.requireMock('./Context/Context.tsx')
and the terminal is returning,
Expected: "!@#$"
Received: ""
372 | fireEvent.blur(input as Element);
373 |
> 374 | expect(input.value).toBe('!@#$')
| ^
375 |
376 | await new Promise(resolve => setTimeout(resolve, 10));
377 |
PLEASE HELP, spent about 3 days on this, and at this point I am over it
It seems like:
fireEvent.blur(input as Element);
is causing the issue. Can you dispose of it?
Please cut this down to a minimal reproducible example. Mocking the context is probably not a very good idea.
@jonrsharpe What would you suggest when testing components that use context?