I am testing api request call using jest and react testing library , here is my codes.
Live demo live demo
utils/api.js
import axios from "axios";
const instance = axios.create({
withCredentials: true,
baseURL: process.env.REACT_APP_API_URL,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
});
export default instance;
export async function get(url, params) {
const response = await instance({
method: "GET",
url: url,
params: params,
});
return response;
}
mock/api.js
const mockResponse = {
data: {
attributes: {
first_name: "Jeff",
last_name: "Bezo's",
},
},
};
export default {
get: jest.fn().mockResolvedValue(mockResponse),
};
Home.js
import React, { useState, useEffect } from "react";
function Home() {
const [user, setUser] = useState();
const getUser = useCallback(async () => {
try {
const response = await api.get("/users/self");
console.log("data response..", response.data);
setUser(response.data.attributes.first_name);
} catch (error) {}
}, [dispatch]);
useEffect(() => {
getUser();
}, []);
return <div data-testid="user-info" > Welcome {user}</div>;
}
export default Home;
Home.test.js
import React, { Suspense } from "react";
import { render, cleanup, screen } from "#testing-library/react";
import "#testing-library/jest-dom/extend-expect";
import Home from "../../editor/Home";
import { Provider } from "react-redux";
import { store } from "../../app/store";
import Loader from "../../components/Loader/Loader";
const MockHomeComponent = () => {
return (
<Provider store={store}>
<Suspense fallback={<Loader />}>
<Home />
</Suspense>
</Provider>
);
};
describe("Home component", () => {
it("should return a user name", async () => {
render(<MockHomeComponent />);
const userDivElement = await screen.findByTestId(`user-info`);
expect(userDivElement).toBeInTheDocument();
screen.debug();
});
afterAll(cleanup);
});
Problem:
When I run npm run test test is passed but in the screen.debug() results I dont see the user name returned as expected I just see Welcome. but it should be welcome Jeff.
What am I doing wrong here? any suggestions will be appreciated
Related
I have a JWT-based API. It rotates the tokens on every response. I have a custom provider that manages this.
I'm trying to figure out how I would use React Router v6.4 data router with this setup. Specifically, I'd like to use the loader / action functions for getting the data, but those don't support useContext and I'm not sure how to pass that in.
I'd like dashboardLoader to call the API with the current set of tokens as headers that AuthContext is managing for me.
The goal is to have the loader function fetch some data to display on the dashboard and to use the get() call from the AuthProvider.
My current alternative is to just do it inside the Dashboard component but would like to see how to do this with a loader.
The relevant files:
// App.js
import "./App.css";
import { createBrowserRouter } from "react-router-dom";
import "./App.css";
import Dashboard, { loader as dashboardLoader } from "./dashboard";
import AuthProvider from "./AuthProvider";
import axios from "axios";
function newApiClient() {
return axios.create({
baseURL: "http://localhost:3000",
headers: {
"Content-Type": "application/json",
},
});
}
const api = newApiClient();
export const router = createBrowserRouter([
{
path: "/",
element: (<h1>Welcome</h1>),
},
{
path: "/dashboard",
element: (
<AuthProvider apiClient={api}>
<Dashboard />
</AuthProvider>
),
loader: dashboardLoader,
},
]);
// AuthProvider
import { createContext, useState } from "react";
const AuthContext = createContext({
login: (email, password) => {},
isLoggedIn: () => {},
get: async () => {},
post: async () => {},
});
export function AuthProvider(props) {
const [authData, setAuthData] = useState({
client: props.apiClient,
accessToken: "",
});
async function login(email, password, callback) {
try {
const reqData = { email: email, password: password };
await post("/auth/sign_in", reqData);
callback();
} catch (e) {
console.error(e);
throw e;
}
}
function isLoggedIn() {
return authData.accessToken === "";
}
async function updateTokens(headers) {
setAuthData((prev) => {
return {
...prev,
accessToken: headers["access-token"],
};
});
}
async function get(path) {
try {
const response = await authData.client.get(path, {
headers: { "access-token": authData.accessToken },
});
await updateTokens(response.headers);
return response;
} catch (error) {
console.error(error);
throw error;
}
}
async function post(path, data) {
try {
const response = await authData.client.post(path, data, {
headers: { "access-token": authData.accessToken },
});
await updateTokens(response.headers);
return response.data;
} catch (error) {
// TODO
console.error(error);
throw error;
}
}
const context = {
login: login,
isLoggedIn: isLoggedIn,
get: get,
post: post,
};
return (
<AuthContext.Provider value={context}>
{props.children}
</AuthContext.Provider>
);
}
// Dashboard
import { useContext } from "react";
import { Navigate } from "react-router-dom";
import AuthContext from "./AuthProvider";
export function loader() {
// TODO use auth context to call the API
// For example:
// const response = await auth.get("/my-data");
// return response.data;
}
export default function Dashboard() {
const auth = useContext(AuthContext);
if (!auth.isLoggedIn()) {
return <Navigate to="/" replace />;
}
return <h1>Dashboard Stuff</h1>;
}
Create the axios instance as you are, but you'll tweak the AuthProvider to add request and response interceptors to handle the token and header. You'll pass a reference to the apiClient to the dashboardLoader loader function as well.
AuthProvider
Store the access token in a React ref and directly consume/reference the passed apiClient instead of storing it in local component state (a React anti-pattern). Add a useEffect hook to add the request and response interceptors to maintain the accessTokenRef value.
export function AuthProvider({ apiClient }) {
const accessTokenRef = useRef();
useEffect(() => {
const requestInterceptor = apiClient.interceptors.request.use(
(config) => {
// Attach current access token ref value to outgoing request headers
config.headers["access-token"] = accessTokenRef.current;
return config;
},
);
const responseInterceptor = apiClient.interceptors.response.use(
(response) => {
// Cache new token from incoming response headers
accessTokenRef.current = response.headers["access-token"];
return response;
},
);
// Return cleanup function to remove interceptors if apiClient updates
return () => {
apiClient.interceptors.request.eject(requestInterceptor);
apiClient.interceptors.response.eject(responseInterceptor);
};
}, [apiClient]);
async function login(email, password, callback) {
try {
const reqData = { email, password };
await apiClient.post("/auth/sign_in", reqData);
callback();
} catch (e) {
console.error(e);
throw e;
}
}
function isLoggedIn() {
return accessTokenRef.current === "";
}
const context = {
login,
isLoggedIn,
get: apiClient.get,
post: apiClient.post,
};
return (
<AuthContext.Provider value={context}>
{props.children}
</AuthContext.Provider>
);
}
Dashboard
Note here that loader is a curried function, e.g. a function that consumes a single argument and returns another function. This is to consume and close over in callback scope the instance of the apiClient.
export const loader = (apiClient) => ({ params, request }) {
// Use passed apiClient to call the API
// For example:
// const response = await apiClient.get("/my-data");
// return response.data;
}
App.js
import { createBrowserRouter } from "react-router-dom";
import axios from "axios";
import "./App.css";
import Dashboard, { loader as dashboardLoader } from "./dashboard";
import AuthProvider from "./AuthProvider";
function newApiClient() {
return axios.create({
baseURL: "http://localhost:3000",
headers: {
"Content-Type": "application/json",
},
});
}
const apiClient = newApiClient();
export const router = createBrowserRouter([
{
path: "/",
element: (<h1>Welcome</h1>),
},
{
path: "/dashboard",
element: (
<AuthProvider apiClient={apiClient}> // <-- pass apiClient
<Dashboard />
</AuthProvider>
),
loader: dashboardLoader(apiClient), // <-- pass apiClient
},
]);
I use postMessage to get the token from the mobile client. Js client sends request using requestRefresh function with postMessage to receive JWT token. Mobile clients execute JS code using a method call, which is described inside the WebView. I save the token in a cookie when I receive it in webview. I successfully get a token the first time I render a component, but I have a problem with updating the token asynchronously in the Apollo client when an "Unauthenticated" or "Invalid jwt token" error occurs.
I don't understand how I can call the call and response function from the mobile client asynchronously inside the onError handler and save the token.
I've reviewed several resources on this, StackOverflow answers 1, 2, Github examples 3, 4, and this blog post 5, but didn't find similar case
.
index.tsx
import React, { Suspense, useState, useEffect, useCallback, useMemo } from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { ApolloClient, InMemoryCache, createHttpLink, ApolloProvider, from } from '#apollo/client';
import { setContext } from '#apollo/client/link/context';
import { onError } from '#apollo/client/link/error';
import { App } from 'app';
import Cookies from 'universal-cookie';
const cookies = new Cookies();
const httpLink = createHttpLink({
uri: process.env.API_HOST,
});
const authLink = setContext((_, { headers }) => {
const token = cookies.get('token');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
},
};
});
const errorLink = onError(({ graphQLErrors, operation, forward }) => {
if (graphQLErrors)
for (const err of graphQLErrors) {
switch (err?.extensions?.code) {
case 'UNAUTHENTICATED':
// error code is set to UNAUTHENTICATED
//How to call and process a response from a mobile client here?
const oldHeaders = operation.getContext().headers;
operation.setContext({
headers: {
...oldHeaders,
authorization: token ? `Bearer ${token}` : '',
},
});
// retry the request, returning the new observable
return forward(operation);
}
}
});
const client = new ApolloClient({
cache: new InMemoryCache({
typePolicies: {
User: {
keyFields: ['userId'],
},
},
}),
link: from([errorLink, authLink, httpLink]),
uri: process.env.API_HOST,
connectToDevTools: process.env.NODE_ENV === 'development',
});
import React, { useEffect, useState, useCallback, useMemo } from 'react';
import Cookies from 'universal-cookie';
interface IMessage {
action: string;
data?: {
text: string;
old_jwt?: string;
};
}
enum Actions {
refreshJWT = 'refresh_jwt',
}
interface IMessageEventData {
action: Actions;
success: boolean;
payload: {
data: string;
};
}
export const Index: React.FC = () => {
const cookies = new Cookies();
const token = cookies.get('token');
const message = useMemo((): IMessage => {
return {
action: Actions.refreshJWT,
data: {
text: 'Hello from JS',
...(token && { old_jwt: token }),
},
};
}, [token]);
const requestRefresh = useCallback(() => {
if (typeof Android !== 'undefined') {
Android.postMessage(JSON.stringify(message));
} else {
window?.webkit?.messageHandlers.iosHandler.postMessage(message);
}
}, [message]);
// #ts-ignore
window.callWebView = useCallback(
({ success, payload, action }: IMessageEventData) => {
if (success) {
if (action === Actions.refreshJWT) {
cookies.set('token', payload.data, { path: '/' });
}
} else {
throw new Error(payload.data);
}
},
[requestRefresh]
);
useEffect(() => {
requestRefresh();
}, []);
return (
<BrowserRouter>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</BrowserRouter>
);
};
ReactDOM.render(<Index />, document.getElementById('root'));
I just started learning javascript and react-redux, and I'm using useEffect to call POST method. So, I am wondering how to make it not send request to my backend whenever I open or refresh website
my HTTP Post looks like:
export const sendItemData = (items) => {
return async () => {
const sendRequest = async () => {
const response = await fetch("http://localhost:51044/api/Items", {
method: "POST",
body: JSON.stringify(items.Items),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
credentials: "same-origin",
});
if (!response.ok) {
throw new Error("Sending data failed!");
}
};
try {
await sendRequest();
} catch (error) {
console.log(error);
}
};
};
and my App.js looks like:
import React from "react";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import Items from "./components/Items ";
import { sendItemData } from "./store/items-actions";
function App() {
const dispatch = useDispatch();
const sendItems = useSelector((state) => state.items);
useEffect(() => {
dispatch(sendItemData(sendItems));
}, [sendItems, dispatch]);
return <Items />;
}
export default App;
Ok, this is my way, tray it
export function MyComp(props) {
const initial = useRef(true)
useEffect(() => {
if (!initial.current) {
// Yoyr code
} else {
// Mark for next times
initial.current = false;
}
}, [args]);
return (
<YourContent />
);
}
I have an app I'm adding integration tests to for learning React Testing Library.
It's built in MERN stack, along with Redux for state management.
My test wrapper is a standard setup:
import React from 'react';
import { render as rtlRender } from '#testing-library/react';
import { createStore, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';
const render = (
ui,
{
initialState,
store = createStore(rootReducer, compose(applyMiddleware(thunk))),
...renderOptions
} = {}
) => {
const Wrapper = ({ children }) => {
return <Provider store={store}>{children}</Provider>;
};
return rtlRender(ui, { wrapper: Wrapper, ...renderOptions });
};
export * from '#testing-library/react';
export { render };
At the moment I'm trying to test a login form and errors that are returned when fields aren't valid.
import React from 'react';
import { Router } from 'react-router';
import '#testing-library/jest-dom';
import { createMemoryHistory } from 'history';
import { render, screen, fireEvent, waitFor } from '../../../utils/test-utils';
import Login from '../login';
jest.mock('axios', () => {
return {
post: jest.fn()
};
});
describe('<Login/>', () => {
beforeEach(() => {
// Some requirements for the component to render in the test
const history = createMemoryHistory();
const state = '';
history.push('/', state);
render(
<Router history={history}>
<Login history={history} />
</Router>
);
});
test('should show empty email error', async () => {
fireEvent.input(screen.getByRole('textbox', { name: /email/i }), {
target: {
value: ''
}
});
fireEvent.submit(screen.getByRole('button', { name: /login/i }));
await waitFor(() => {
expect(screen.getByText(/email field is required/i)).toBeInTheDocument();
});
});
});
Unfortunately, when I run this test it gives me TypeError: Cannot read property 'then' of undefined and I can't figure out why
My action looks like:
export const loginUser = (userData) => (dispatch) => {
return axios
.post('/api/users/login', userData)
.then((res) => {
const { token } = res.data;
localStorage.setItem('jwtToken', token);
setAuthToken(token);
const decoded = jwt_decode(token);
dispatch(setCurrentUser(decoded));
})
.catch((err) =>
dispatch({
type: GET_ERRORS,
payload: err.response.data
})
);
};
Instead of testing the actions/reducers in my codebase I'd rather test what the user should see, which is what I've read Testing Library encourages.
I'm also using redux hooks - useDispatch/useSelector, throughout my app.
Any help would be grateful :)
I have the following code implemented (PLEASE keep in mind, I don't want to use redux)
My global store hook:
// store.tsx - custom store hook
import { useState, useEffect } from "react";
let globalState = {};
let listeners = [];
let actions = {};
export const useStore = () => {
const setState = useState(globalState)[1];
const dispatch = async (actionIdentifier, payload) => { // needed to add async/await in order to wait the async/await in the custom hooks for actions, i.e. for fetching
const newState = await actions[actionIdentifier](globalState, payload);
globalState = { ...globalState, ...newState };
for (const listener of listeners) {
listener(globalState);
}
};
useEffect(() => {
listeners.push(setState);
return () => {
listeners = listeners.filter((li) => li !== setState);
};
}, [setState, shouldListen]);
return [globalState, dispatch];
};
export const initStore = (userActions, initialState) => {
if (initialState) {
globalState = { ...globalState, ...initialState };
}
actions = { ...actions, ...userActions };
};
import { initStore } from "./store";
the file responsible for loading actions
// loading-store.tsx
const configureStore = () => {
const actions = {
SET_LOADING_START: (currentState) => {
return { loading: true };
},
SET_LOADING_END: (currentState) => {
return { loading: false };
},
};
initStore(actions, {
loading: false,
});
};
export default configureStore;
and the file responsible for fetching:
// fetching-store.tsx
import { initStore } from "./store";
import { getData } from "src/api/ResourceService";
const configureStore = () => {
function fetchData() {
const fetch = async () => {
try {
const res = await getData();
console.log("[FETCH] Data:", res.data);
return res.data;
} catch (err) {
console.error("[FETCH] Error", err);
return err;
}
};
return fetch();
}
const actions = {
FETCH: async (currentState) => {
const newData = await fetchData();
return { myFetchedData: newData };
},
};
initStore(actions, {
myFetchedData: [],
});
};
export default configureStore;
the following index.tsx file:
// index.tsx
import React from "react";
import ReactDOM from "react-dom";
import "./assets/css/simpl-newton-bootstrap.css";
import "../node_modules/react-grid-layout/css/styles.css";
import "../node_modules/react-resizable/css/styles.css";
import { BrowserRouter } from "react-router-dom";
import * as serviceWorker from "./serviceWorker";
import App from "./App";
import { ThemeProvider } from "src/context/ThemeContext";
import fetchingStore from "src/hooks-store/fetching-store";
import loadingStore from "src/hooks-store/loading-store";
fetchingStore();
loadingStore();
ReactDOM.render(
<ThemeProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</ThemeProvider>,
document.getElementById("root")
);
serviceWorker.unregister();
The QUESTION is how can I set loading to true/false during the fetch which is done in fetchiing-store.tsx
This is the implementation in the Component where I call the fetch:
// myComponent.tsx
import React, { useEffect } from "react";
import { useStore } from "src/hooks-store/store";
const myComponent = () => {
const [state, dispatch] = useStore();
const data = state.myFetchedData;
useEffect(() => {
dispatch("FETCH");
}, []);
return (
<>
// some code where data will be used ...
</>
);
}
export default myComponent;
I did try to place it in the useEffect of myComponent.tsx as:
...
useEffect(() => {
dispatch("SET_LOADING_START");
dispatch("FETCH");
}, []);
...
and than manually in fetching-store.tsx
...
const actions = {
FETCH: async (currentState) => {
const newData = await fetchData();
return { myFetchedData: newData, loading: false };
},
};
initStore(actions, {
myFetchedData: [],
loading: false,
});
...
But it is a bit dirty. If anyone has a better solution or an option?
Another question is, is it at all a good idea to use async/await call in the actions store?