I'm a newbie on test driven development, and I came across a section regarding testing/mocking a fetch api. But I'm struggling to write my own test. I built a simple weather app just to test/mock the fetch using jest. But the test keeps failing. I keep getting errors like:
Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: And not just that, I do not know where I am going wrong, so I came here to ask for tips on how I could mock/improve my test so that it can be successful. H
Here's my React code: (App.js)
const [search, setSearch] = useState('');
const [weather, setWeather] = useState({});
const handleChange = (e) => {
setSearch(e.target.value)
}
//function returns a promise
const WeatherData = async (e) => {
if (e.key === "Enter") {
await fetch(`${api.baseURL}weather?q=${search}&appid=${api.key}`)
.then(data => data.json())
.then(city => {
//console.log(city)
setSearch('')
setWeather(city)
})
}
}
const currentDate = (d) => {
let months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
let day = days[d.getDay()];
let month = months[d.getMonth()];
let year = d.getFullYear();
let date = d.getDate();
return `${day} ${date} ${month} ${year}`
}
return (
<div className="App">
<h2>International Weather</h2>
<div className="wrapper">
<input type="text" id="search-field" placeholder='Search...' onChange={handleChange} onKeyPress={WeatherData} />
{(typeof weather.main != "undefined") ? (
<div className='weather-box'>
<h2>{weather.name}, {weather.sys.country}</h2>
<h2> {currentDate(new Date())} </h2>
<div id="weather">
<div className="details" id="degrees">{(weather.main.temp - 273.15).toFixed(2)}°C</div>
<div className="details" id="clouds">{weather.weather[0].main}</div>
</div>
</div>
) : (" ")}
</div>
</div>
);
}
And my App.js code:
import { render, screen } from "@testing-library/react";
import App from "./App";
//creating a snapshot test to test if the rendered component is the same as the snapshot app
test("snapshot is correct", () => {
const tree = render(<App />);
expect(tree).toMatchSnapshot();
});
//test whether the function works
test("fetch works correctly", async () => {
App(
JSON.stringify({
results: [{ user: "mandla", age: 43 }],
})
).then((data) => {
expect(data).toBe();
});
});
Would appreciate if anyone can help me understand the problem and why my solution is not working.
Type ... is missing the following properties from type Response...
– Alphonsoalphonsus