How to test a function from a svelte component with jest?

Viewed 687

There is a lot of documentation on the internet to test svelte component with jest, calling render functions and simulating browser events. This is nice, but how can I test a function inside a svelte component?

mycompoment.svelte

<script>
function veryComplicated(foo) {
     ...
}
</script>

<div>...</div>

mycomponent.test.js

import { veryComplicated } from "./mycomponent.svelte"

test('it works', async () => {
    expect(vercomplicated("foo").toBe("bar"))
})

jest

 FAIL  src/mycomponent.test.ts
  ● Test suite failed to run

    src/mycomponent.test.ts:1:10 - error TS2614: Module '"*.svelte"' has no exported member 'veryComplicated'. Did you mean to use 'import veryComplicated from "*.svelte"' instead?

    1 import { veryComplicated } from "./mycomponent.svelte"
               ~~~~~~~~~~~~~~~

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.697 s
Ran all test suites.

Adding export before the veryComplicated definition does not help.

How can I test the veryComplicated function?

2 Answers

You can export a function using a module context script block.

<script context="module">
    export veryComplicated() {
        // ...
    }
</script>

<div>...</div>

Then you can do import { veryComplicated } from './mycomponent.svelte' as you were originally trying to do.

https://svelte.dev/tutorial/module-exports

Found it. I had to call render

mycomponent.test.js

import { render } from '@testing-library/svelte'
import MyComponent from "./mycomponent.svelte"

test('it works', async () => {
    const component = render(MyComponent)
    expect(component.verComplicated("foo").toBe("bar")
})

And it is needed to export the veryComplicated function.

Related