svelte-hash-router icon indicating copy to clipboard operation
svelte-hash-router copied to clipboard

TypeError: routes.set is not a function unit tests

Open ritchieanesco opened this issue 4 years ago • 3 comments

I'm writing unit tests to validate correct pages are appearing on navigation change. I am using Svelte Testing Library.

I can not provide the actual code due to privacy reasons but here is the gist of it.

App.svelte

<script lang="ts">
  import { Router, routes } from "svelte-hash-router"
  import PageOne from "./PageOne.svelte"
  routes.set({
    "page-one": PageOne
  })
</script>

App.test.ts

it('should render header', async () => {
  const { getByTestId } = render(App)
  window.location.href = "/#/page-one"
  await waitFor(() => getByTestId("header"))
  expect(getByTestId("title")).toBeInTheDocument()
})

it("should render main", async () => {
  const { getByTestId } = render(App)
  window.location.href = "/#/page-one"
  await waitFor(() => getByTestId("main"))
})

When I run the tests the first one passes, but the second test outputs the following error: TypeError: routes.set is not a function

I had a look through the code and noticed this:

https://github.com/pynnl/svelte-hash-router/blob/1afbdc9b7945b8f3a7d576692c58ab97ab722652/src/utils/routes.js#L54

I'm wondering why set needs to be removed.

ritchieanesco avatar Oct 26 '20 06:10 ritchieanesco

Currently routes can only be set once. Based on your code, I guess you are initializing it inside a component. The component can be mounted many times, thus calling routes.set many times. You should set the routes in the entry js file, before any components. You can see the example code here.

tienpv222 avatar Oct 29 '20 00:10 tienpv222

Thanks for responding. There was a reason I moved it there, having routes initialised in the entry file means the component in my tests has no way of initialising the svelte-hash-router store.

To make it work for now i've just added a condition for set.

ritchieanesco avatar Oct 29 '20 00:10 ritchieanesco

@ritchieanesco Sorry, I should have added the ability to create different instances of routes, rather than making it global. I'll try to add it when I have time, kinda busy with coop.

tienpv222 avatar Oct 29 '20 03:10 tienpv222