How do I test axios in Jest?

Without using any other libraries: import * as axios from “axios”; // Mock out all top level functions, such as get, put, delete and post: jest.mock(“axios”); // … test(“good response”, () => { axios.get.mockImplementation(() => Promise.resolve({ data: {…} })); // … }); test(“bad response”, () => { axios.get.mockImplementation(() => Promise.reject({ … })); // … }); … Read more

What is the best way to access redux store outside a react component?

Export the store from the module you called createStore with. Then you are assured it will both be created and will not pollute the global window space. MyStore.js const store = createStore(myReducer); export store; or const store = createStore(myReducer); export default store; MyClient.js import {store} from ‘./MyStore’ store.dispatch(…) or if you used default import store … Read more

Load images based on dynamic path in ReactJs

Assuming that you are using webpack, you need to import the image in order to display it like <img src={require(‘images/06.jpg’)} alt=”product” /> Now that your image data is dynamic, directly specifying the import path like <img src={require(image)} alt=”product” /> doesn’t work. However you can import the image by making use of template literals like <img … Read more

How can I display a modal dialog in Redux that performs asynchronous actions?

The approach I suggest is a bit verbose but I found it to scale pretty well into complex apps. When you want to show a modal, fire an action describing which modal you’d like to see: Dispatching an Action to Show the Modal this.props.dispatch({ type: ‘SHOW_MODAL’, modalType: ‘DELETE_POST’, modalProps: { postId: 42 } }) (Strings … Read more

React useEffect in depth / use of useEffect?

useEffect(callback); // Example useEffect(() => { console.log(“executed after render phase”); return () => { console.log(“cleanup function after render”); }; }); Runs on every component render. Typically used for debugging, analogous to function’s body execution on every render: const Component = () => { callback() return <></>; }; Note: There is still a difference, in execution … Read more