jestjssveltets-jestbabel-jest

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


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?


Solution

  • 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.veryComplicated("foo")).toBe("bar")
    })
    

    And it is needed to export the veryComplicated function in the original file:

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