Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fetch returning undefined rather than result #202

Open
DoryZi opened this issue May 16, 2021 · 2 comments
Open

fetch returning undefined rather than result #202

DoryZi opened this issue May 16, 2021 · 2 comments

Comments

@DoryZi
Copy link

DoryZi commented May 16, 2021

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?

@yinzara
Copy link
Collaborator

yinzara commented May 16, 2021

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

@yinzara
Copy link
Collaborator

yinzara commented May 16, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants