jest-fetch-mock
jest-fetch-mock copied to clipboard
fetch returning undefined rather than result
I have a create react app project. With the following component:
const LegalPage: React.FC = () => {
const classes = useStyles()
const { documentType } = useParams<{documentType: string}>()
const [content, setContent] = useState<string>()
const {t, i18n} = useTranslation()
useEffect(() => {
const loadFile = async () => {
try {
const response = await fetch(`/legalDocs/${i18n.language}/${documentType}.html`)
const htmlContent = (response.status === 200) ? await response.text() :
(`<p>Error reading ${documentType}. please try again, if issue persists please let us know at [email protected]</p>`)
setContent(htmlContent)
} catch (e) {
console.error(e)
setContent(`<p>Error reading ${documentType}. please try again, if issue persists please let us know at [email protected]</p>`)
}
}
loadFile()
}, [documentType, i18n.language])
return (<Container className={classes.root}>
<Typography variant="body1">
{(content) ? parse(content) : ''}
</Typography>
</Container>
)
}
export default LegalPage
I have setupTests.ts
// setupTests.ts
import jestFetchMock from 'jest-fetch-mock'
jestFetchMock.enableMocks()
the and test: const enTermsOfUse = '
TermsOfUse
'
fetch.mockResponse({
status: 200,
text: () => Promise.resolve(enTermsOfUse)
})
test('loading privacy policy in bulgaria works ok ', async () =>{
htmlContent = bgPrivacyPolicy
param = 'privacy-policy'
render(<LegalPage />)
})
How the await fetch in the LegalPage always returns undefined. Am I doing something wrong or is there a bug?
Have you set "resetMocks" Jest configuration to "false"?
Also your test should have "mockResponse(enTermsOfUse)". No need for the complex response you have.
Also where are you making that call? It should be inside the test case itself or in a beforeEach