masakudamatsu / mima

My Ideal Map, a web app to allow users to save places with **external links** on Google Maps
https://www.my-ideal-map.app
MIT License
1 stars 0 forks source link

Test loading component for Next.js dynamic import #178

Open masakudamatsu opened 2 years ago

masakudamatsu commented 2 years ago

Currently we cannot test whether the message "Loading..." is shown (briefly) after clicking the search button.

masakudamatsu commented 2 years ago

Set up

function deferred() {
  let resolve, reject
  const promise = new Promise((res, rej) => {
    resolve = res
    reject = rej
  })
  return {promise, resolve, reject}
}

Then use as follows (for an example of Geolocation API)

const {promise, resolve} = deferred()
  window.navigator.geolocation.getCurrentPosition.mockImplementation(
    callback => {
      promise.then(() => callback(fakePosition))
    },
  )

  render(<Location />)

  expect(screen.getByLabelText(/loading/i)).toBeInTheDocument()

  await act(async () => {
    resolve()
    await promise
  })

  expect(screen.queryByLabelText(/loading/i)).not.toBeInTheDocument()

source: https://github.com/kentcdodds/testing-react-apps/blob/main/src/__tests__/final/06.js

description: https://github.com/kentcdodds/testing-react-apps/blob/main/src/__tests__/exercise/06.js

masakudamatsu commented 2 years ago

The above method cannot directly be applied, because we need to figure out how to mock the implementation of dynamic() function when its promise is 'pending'.

Its source code here: https://github.com/vercel/next.js/blob/canary/packages/next/shared/lib/dynamic.tsx

masakudamatsu commented 1 year ago

We can now use interceptIndefinitely test utility, as used in saved-places.cy.js.