I'm using jest
with react testing library
to provide basic testing for my React app. I have mocked the REST calls with msw
.
Unfortunately one of the 3rd party libraries I'm using doesn't seem to render output properly in those tests and as I am more interesting in testing the whole flow than precise results I've decided to mock it and replace with a dummy implementation.
The library is react-photo-album, and I'm importing it in my component as:
import PhotoAlbum from "react-photo-album";
My test looks like:
it('loads photos', async () => {
//mocking goes here
const { container } = render(<MemoryRouter><Gallery /></MemoryRouter>);
screen.debug();
await waitFor(() => {
expect(container.getElementsByClassName('mockedComponent').length).toBe(1);
});
});
I'm mostly interested in the result after msw
responds to the rest calls providing actual data, but for now I'd be happy to at least see the PhotoAlbum component replaced at all in the debug view. Yet, it doesn't seem to be affected at all. Instead original component is rendered.
Now, what I've tried for mocking (already dropping any fancy logic):
jest.doMock('react-photo-album', () => ({
PhotoAlbum: () => <div className="mockedComponent" />,
}));
jest.mock('react-photo-album', () => ({
__esModule: true,
PhotoAlbum: () => <div className="mockedComponent" />,
}));
jest.mock('react-photo-album', () => ({
__esModule: true,
default: () => <div className="mockedComponent" />,
}));
jest.mock('PhotoAlbum', () => (props) => {
return <div className="mockedComponent" />;
});
plus multiple variations of those, including mock
and doMock
and even simply:
jest.mock('react-photo-album');
But my component seems to be untouched!. With mock method I mostly get error of:
The module factory of
jest.mock()
is not allowed to reference any out-of-scope variables. Invalid variable access: _jsxFileName
but doMock seems to solve this problem.
So what am I doing wrong? I feel like I'm missing some detail. For the record neither React or jest are the tools I'm normally used to work with. I've also seen answers like: How to mock a third party React component using Jest?, but it just doesn't seem to work.