score:2
Accepted answer
Test case
As you can see you passed empty array which does not contain orders
test("mock fetch call, empty responce from db should return no data",
async () => {
const fakeResponse = []; <-- empty array which does not contain orders
const userId = "1234567";
jest.spyOn(window, "fetch").mockImplementation(() => {
const fetchResponse = {
json: () => Promise.resolve(fakeResponse),
};
return Promise.resolve(fetchResponse);
});
await act(async () => {
render(<WelcomePage location={userId} />, container);
});
expect(container.innerHTML).toContain("no data");
window.fetch.mockRestore();
}
);
Because data is empty when it tried to access orders which is undefined
and undefined
does not have map
function
{data.orders.map((order, index) => ( <-- problems here
<ul className="orderBox" key={order.toString()+index}>
<li className="orderLink">
<Link
to={{
pathname: "/OrderDetails",
state: {
orderNumber: order.rollNumber,
userID: this.state.userID,
},
}}
>
Order number: {order.rollNumber}
</Link>
</li>
<li> Customer name: {order.customerFullName}</li>
</ul>
))}
You can change it like this:
{data && data.orders && data.orders.map((order, index) => ( <-- changes
<ul className="orderBox" key={order.toString()+index}>
<li className="orderLink">
<Link
to={{
pathname: "/OrderDetails",
state: {
orderNumber: order.rollNumber,
userID: this.state.userID,
},
}}
>
Order number: {order.rollNumber}
</Link>
</li>
<li> Customer name: {order.customerFullName}</li>
</ul>
))}
Note:
- As you are passing
fakeResponse
as array you need to updatesetState
inside fetch inWelcomePage.js
to
if (data && data[0] && data[0]['data']) {
this.setState({
data: data[0]['data'], <-- changes
isLoading: false,
});
}
- or change
fakeResponse
to:
const fakeResponse = {
data: {
userId: 1234567,
userForename: "Joe",
userSurname: "Bloggs",
orders: [
{
orderNumber: 10000000001,
customerFullName: "Mrs Joes Bloggs",
userId: 1234567
},
]
}
};
setState to:
if (data && data['data']) {
this.setState({
data: data['data'], <-- changes
isLoading: false,
});
}
And condition to check if data is empty:
if (Object.keys(data).length === 0) {
return <p> no data found</p>;
}
score:1
fakeRespose
is array of object.
const fakeResponse = [
{
data: {
userId: 1234567,
userForename: "Joe",
userSurname: "Bloggs",
orders: [
{
orderNumber: 10000000001,
customerFullName: "Mrs Joes Bloggs",
userId: 1234567
},
]
}
}
];
So following passes.
if (data.length === 0) {
return <p> no data found</p>;
}
But data
is array so orders
doesn't exist.
Source: stackoverflow.com
Related Query
- How can mock the value of a state and data in my react test
- How can we reset the data and state of the mutation in RTK query , like reset function in React Query for mutation?
- How can I cache data that I already requested and access it from the store using React and Redux Toolkit
- React testing - How can I mock or inject data in the store to be provided as props to component
- How to check the value of a nested React component in a unit test with Enzyme and Jest
- How do I correctly add data from multiple endpoints called inside useEffect to the state object using React Hooks and Context API?
- Can I use mock data and proxy api data at the same time in my react project when using node express as a proxy server?
- How can I redirect to another component in react and pass the state that I set in the previous component?
- How can I set the default state of a checkbox based on value in firestore in react table
- I have a data inside the state in T and Z format and React input accepts in the HH:MM ss format so how to convert
- How can I make react render the new state modifications after I have updated the state with hooks and context
- how can i stop this counter and put the final value in databases using react js axios
- In React How can I fetch data and render a single object in a states array without mapping the whole thing?
- How can I store all the dynamic values and attribute labels in a state in react js
- How can I pass a value from the backend to a React frontend and use that value in the CSS for the frontend?
- React - How to use the current state value as a variable so i can set as a index inside an array
- Filtering Json data based on key and assiging the value to state in react
- How can i store the value of a React input element and use it in some other elements
- How can I get the value of an input field and use it in URL in React
- How can I add a checkbox to each element in the list and to be able to control it through state in my react app?
- How can I store previous values instead of storing the value in array of objects in react state
- Using react, how can I create a function to set the state that takes the state name and value as arguments?
- How can I test react component that fetches the data from firestore?
- how can I set the reducer's return value to state object in component in react js
- How can I prevent to add data if the object property value is different using react js
- How can we hold/persist the selected dropdown value after submit and reset the textarea in react hooks form
- How can I iterate through an object containing arrays in React and the object is in the state
- How to test if state of a component is changed by the function using jest and Enzyme in React TDD
- How can I mock an imported React hook/module and test that it's being called properly on different test cases using Jest
- How can I update State in React using the React-Select Component and User Selection?
More Query from same tag
- How can I open csv file received from axios get response in new window
- How to select a <td> with a specific value?
- How to render string OR Component?
- Nginx routes and refresh cause 404
- How implement toggle with Rxjs
- How to track email is opened or not, email is delivered or not, email bounced or not?
- axios get request for local data redux
- mapStateToProps and mapDispatchToProps is not sending props to component
- How dispaly an svg on the option of select with ReactJs?
- Create React App 4.0 cannot resolve image path in public folder
- CustomError typescript, wrong instance of the error inside the component
- How do I change div positions from horizontally aligned to vertically aligned when a condition is true?
- State variable hook not working with useEffect callback
- React render instagram feeds from data.json
- React render based on OR operator
- React Data Grid: Can we restrict input while editing as numeric only?
- DOM cast to string
- how do I use Axios to post to a database in a form?
- How to set two properties for a React component as optional depending on another property using TypeScript?
- How to remove the red line for a react button containing a js link
- Is this table possible in HTML
- What is the alternative component of message.error() [antd] in material UI?
- How can I fix my code to display correct index of array
- How to implement Finnhub.io stock API into a React App
- React useContext from async service with Promise
- How to dynamically write a React.useState function so that you can have as many input types you want from a cms
- Query multiple JSON files with graphQL in Gatsby
- How to prevent form submission on wrong button and only work on right button
- 'Router' cannot be used as a JSX component
- Place getServerSideProps function in an helper