0

I want to export a function from a Svelte component and import it into a Jest test file for testing.

My expected result based on this post is that I can do:

// index.svelte
<script>
  export function updateEnabledSubmitSignup(email, username, password, confirmedPassword) {
      // ...
  }
</script>

and then in my test file:

import Signup from "../src/routes/signup/index.svelte"

describe("signup page logic", () => {
  test("ensure that the signup form button enablement conditions work properly", () => {
    console.log(Signup, "5rm")
    const failureOne = Signup.updateEnabledSubmitSignup()
    expect(failureOne).toBe(false)
  })
})

But running this code gives

tests/signup.test.ts:6:31 - error TS2339: Property 'updateEnabledSubmitSignup' does not exist on type 'typeof SvelteComponentDev'.

    6     const failureOne = Signup.updateEnabledSubmitSignup()

It fails also if I do <script context="module"> with Property 'updateEnabledSubmitSignup' does not exist on type 'typeof SvelteComponentDev'.

If I try a named import like

import { updateEnabledSubmitSignup } from "../src/routes/signup/index.svelte"

then running the test gives error TS2614: Module '"*.svelte"' has no exported member 'updateEnabledSubmitSignup'. Did you mean to use 'import updateEnabledSubmitSignup from "*.svelte"' instead?

Anyone know how to do this please? This reddit post claims "You can use the tag at the top of your component to export a function." But even though I do that, the import fails.

plutownium
  • 1,220
  • 2
  • 9
  • 23

1 Answers1

0

Functions exported from the regular script are on the instance, e.g.

let signup;
onMount(() => signup.updateEnabledSubmitSignup());
<Signup bind:this={signup} />

Functions exported from the context=module script are named exports of the file.

If you get a type error from that, it is because your tooling did not determine the types correctly (it generically says *.svelte instead of the concrete type of this specific component). Question being, why your tests are doing type checking in the first place.

H.B.
  • 166,899
  • 29
  • 327
  • 400
  • I use a `.ts` jest test file! hence why tests are doing type checking. I'll try with `.js` – plutownium Feb 16 '23 at 21:28
  • The build tool plugins for Svelte should be able to generate correct types for each component; you could look into how to write those to `d.ts` files for the tests or maybe this can be integrated another way if you want to stick with TS. – H.B. Feb 16 '23 at 21:48
  • I marked your answer as correct because I was able to write a successful unit test using your advice. One step was to convert my ts test file into a js test file. The other was to use `context="module"` – plutownium Feb 17 '23 at 02:32