I'm running tests via node with Jest, on a Next/React project.
I'm also using cross-fetch as well.
When I try to mock cross-fetch for my component
import crossFetch from 'cross-fetch'
jest.mock('cross-fetch')
crossFetch.mockResolvedValue({
status: 200,
json: () => {{
user : testUser
}},
})
render(<UserProfile />)
The API request in the getServerSideProps always returns 500
export async function getServerSideProps({ query: { userId } }) {
let user = null
let code = 200
try {
let response = await fetch(`https://example.com/users/${userId}`, { method: 'GET' })
let statusCode = response.status
let data = await response.json()
if (statusCode !== 200) {
code = statusCode
} else {
user = data.user
}
} catch (e) {
console.log(e.message)
}
return {
props: {
user,
code,
},
}
}
I have a feel it has something to do with the tests being initiating from Node and testing-library library is simulating a browser, that the actual lib making the request is not being mocked for the correct execution environment (browser in my case). But I'm not entirely sure.
Thanks in advance