I have a simple react application that uses RTK Query and React Router. It makes an API call and it has 2 routes
- unauthorized
- welcome
I need help with testing setup and couple of sample tests using React Test Library and Jest.
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './app/store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<Routes>
<Route path='/app' element={ <App />} />
</Routes>
</BrowserRouter>
</Provider>,
document.getElementById('root')
);
App.js
import React from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import Unauthorized from './features/unauthorized/Unauthorized';
import NotFound from './features/notFound/NotFound';
import RequireAuth from './features/auth/RequireAuth';
import Welcome from './features/welcome/Welcome';
function App() {
return (
<Routes>
<Route index path="unauthorized" element={ <Unauthorized />} />
<Route path="*" element={<NotFound />} />
<Route element={<RequireAuth groups={groups} />}>
<Route path="welcome" element={<Welcome />} />
<Route path="/" element={<Navigate to={welcome} />} />
</Rout>
</Routes>
);
}
export default App;
Unauthorized.js
function Unauthorized(){
return 'Unauthorized';
}
export default Unauthorized;
NotFound.js
function NotFound(){
return 'Not Found!';
}
export default NotFound;
RequireAuth.js
import React from 'react';
import { Navigate, Outlet, useLocation } from 'react-router-dom';
function RequireAuth() {
const location = useLocation();
const isAuthorized = true;
if (isAuthorized) {
return <Outlet />;
} else {
return <Navigate to='unauthorized' state={{ from: location }} replace />
}
}
export default RequireAuth;
Welcome.js
import React from 'react';
import { useGetWelcomeQuery } from './welcomeApi';
function Welcome() {
const { data } = useGetWelcomeQuery();
return (
<div>
<p>Welcome!</p>
<h2>Messages</h2>
{data.map((item) => (
<p key={item.id}>{item.message}</p>
))}
</div>
);
}
export default Welcome;
store.js
import { configureStore } from '@reduxjs/toolkit'
import { welcomeApi } from "../features/welcome/welcomeApi";
export const store = configureStore({
reducer: {
[welcomeApi.reducerPath]: welcomeApi.reducer
},
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(apiSlice.middleware),
devTools: true
});
welcomeApi.js
export const welcomeApi = createApi({
reducerPath: 'welcomeApi',
baseQuery: fetchBaseQuery({ baseUrl: '/api' }),
endpoints: (builder) => ({
getWelcome: builder.query({
query: () => ({
url: '/message'
}),
}),
addWelcome: builder.mutation({
query: (welcomeMessage) => ({
url: '/message',
method: 'POST',
body: welcomeMessage,
}),
}),
updateWelcome: builder.mutation({
query: (welcomeMessage) => ({
url: `message/${id}`,
method: 'PUT',
body: welcomeMessage
}),
}),
}),
});
export const {
useGetWelcomeQuery,
useAddWelcomeMutation,
useUpdateWelcomeMutation
} = welcomeApi;