I want to mock the fetch in the Message function
const Message = () => {
const url = process.env.REACT_APP_BACKEND_URL +"/helloworld"
console.log(url)
const response = fetch(url)
console.log(response)
return response.text
}
export default Message
I should be mocked i the Jest test
import App from './App'
import {render,screen} from '@testing-library/react'
global.fetch = jest.fn(() => Promise.resolve({ text: () => Promise.resolve("Hello World")}))
it('should display hello world', async () => {
render(<App />);
const linkElement = screen.getByText('Hello World');
expect(linkElement).toBeInTheDocument();
})
Coode that should be tested look like this
import React from ‘react’
import Message from ‘./Message’
function App () {
return <Message />
}
export default App ;
When I run the test I get following message
FAIL src/App.test.jsx
✕ should display hello world (147 ms)
● should display hello world
TypeError: Cannot read property 'text' of undefined
6 | const response = fetch(url)
7 | console.log(response)
> 8 | return response.text
| ^
9 | }
10 | export default Message
at Message (src/Message.jsx:8:33)
How do I mock the fetch?