score:3
You don't need to mock the api call. fetch
has its own library tests so you don't need to test if fetch
works. But if you really need to test your method, you can just use jest
- https://facebook.github.io/jest/docs/en/asynchronous.html . Forget the jest-fetch-mock. You can test:
- Was the method
componentDidMount
called? - Was
yourMethod
called? - After
yourMethod
finished, did the change occurred? (Your new state is the expected one?)
Just remember not to test the libraries themselves, or to go very deep into the component tree. You should only test atomically. One thing at a time.
Now:
You can use async/await
or just test the fetch itself. First of all, you should abstract those fetch
'es to their own methods. Now. If all you do is concatenate promises and if u get everything correctly u set the state, you just need to , on the test file, resolve that promise, and on its callback, check if the state changed to what you wanted.
Again, this has all you need to know: https://facebook.github.io/jest/docs/en/asynchronous.html#promises
And if you need one more resource here you go: https://codereviewvideos.com/course/react-redux-and-redux-saga-with-symfony-3/video/testing-javascript-s-fetch-with-jest-happy-path
score:0
The trick here is to assert state/snapshot after the data from remote source are received. Even with mocking it's still goes asynchronously. So you can use e.g. setTimeout to postpone assertion:
import React from "react";
import { shallow } from "enzyme";
import sinon from "sinon";
import fetch from "node-fetch";
sinon.stub(fetch, "Promise").returns(
Promise.resolve({
json: () => Promise.resolve( { name: "Hello" } )
})
);
class Test extends React.Component {
state = {
name: "none"
};
async componentDidMount() {
const res = await fetch( "https://swapi.co/api/people/1" ),
data = await res.json();
this.setState({ name: data.name });
}
render() {
return <h1>{ this.state.name }</h1>;
}
}
describe( "component with fetch", () => {
test( "state gets updated with the fetch", ( done ) => {
const wrapper = shallow( <Test /> );
setTimeout(() => {
wrapper.update();
const state = wrapper.instance().state;
console.log(state);
done();
}, 10 );
});
});
score:0
We generally test the state
that the lifecycle methods have changed by mocking the fetch calls. Avoid using setTimeout
in tests as you never know how much time the fetchMock is gonna take, so you can use await
instead of that. For example:
import React from "react";
import {shallow} from "enzyme";
import fetchMock from "fetch-mock";
import TestComponent from "./TestComponent";
describe(() => {
it("should set the state after fetching data", () => {
// arrange
fetchMock.get(`https://www.example.com`, mockResponse);
const wrapper = shallow(<TestComponent>);
// act
await wrapper.instance().componentDidMount();
// assert
expect(wrapper.state()).toEqual(newStateObject);
})
})
Source: stackoverflow.com
Related Query
- How to test react components when fetch in componentDidMount?
- How do I test async fetch in react componentDidMount with chained promises?
- How to fetch data when a React component prop changes?
- In React Native how can I test my components with Shallow Rendering?
- How to check when the react components get rendered or rerendered
- How to mock functions, and test that they're called, when passed as props in react components?
- How to TEST async calls made in componentDidMount that set the state of React Component
- How to test class components in react
- React Redux - How to dispatch an action on componentDidMount when using mapDispatchToProps in a connected component
- How to test components internal functions with React testing library
- How to unit test a React component that renders after fetch has finished?
- How to update (re-render) the child components in React when the parent's state change?
- How to test react components with mobx observable state
- How to test inner functions defined on Stateless Components in React with Enzyme
- How can I unit test parent react components that call methods on children
- How to mock fetch when testing a React app?
- How to optimize React components with React.memo and useCallback when callbacks are changing state in the parent
- How does React re-use child components / keep the state of child components when re-rendering the parent component?
- React components render correctly in browser, but Jest test errors when rendering: "Only a ReactOwner can have refs"
- React Testing Library: How to test components that contain useLocation()?
- React - How do i force child components to re render when parent state component changes?
- How to mock Publish/subscribe events on React Components when using PubSubJS with Jest/Enzyme?
- how to test a react component after data is fetch in componentDidMount?
- How to test controlled React components with cypress-react-unit-test
- How should I test the composition of React components using HOCs (or should I even test them at all)?
- How can i write a test using React Testing Library to check if hover changes the components style?
- How to fetch api via looped callbacks with React functional components
- How to achieve a 100% test coverage on these ternary expressions in react components
- How to test React components inside react-responsive tags
- how to mock npm uniqid for react unit test when using Jest?
More Query from same tag
- JavaScript Arithmetic's
- Trigger event when the state of child of another component changed in react
- CSS Animate button to appear
- Swap objects in the array without mutating the array
- React NavLink: isActive function throws 'string is not assignable to type string | undefined'
- React - getting inputs
- How can i render an image came from MongoDB in binary data on React.js?
- Webpack server configuration + external libs
- onClick does not work for custom component
- Handling routes after submitting form
- Scroll to bottom of an overflowing div in React
- My query is failing in relay and I don't know why?
- Why is type not assignable to generic type
- Store redux-form's dirty prop in redux store
- Coingecko pagination. Mission impossible
- Cntrl S to submit a from in react JS but input field not working
- styled-components with custom component not applying styles
- React-places-autocomplete -- How can i set state for three inputs whenusing autocompleted?
- How to test API request failures with Redux Saga?
- Render nested route component on new page
- Calling functions inside a map() function in React render()
- Import image from folder in React
- Overlay, disappear on click, reactjs
- Store checkbox values as array in React
- I want to put Component in TableBody tag
- Want to populate dynamic data for rows and columns from state in Collapsible table using material UI for React.js
- Uncaught Error: Objects are not valid as a React child (found: object with keys {todo}). If you meant to render a collection of children, use an array
- TypeError: Cannot read properties of undefined (reading 'main')
- How to list individual key values in an object in React
- How can I do a ternary operator inside a map with the mapping for the true condition but without the mapping for the false