jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
881 stars 116 forks source link

fetch returning undefined rather than result #202

Open DoryZi opened 3 years ago

DoryZi commented 3 years ago

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 info@loanaid.ai</p>`)
      setContent(htmlContent)
      } catch (e) {
        console.error(e)
        setContent(`<p>Error reading ${documentType}. please try again, if issue persists please let us know at info@loanaid.ai</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?

yinzara commented 3 years ago

Have you set "resetMocks" Jest configuration to "false"?

yinzara commented 3 years ago

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