Reputation: 4516
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?
<script>
function veryComplicated(foo) {
...
}
</script>
<div>...</div>
import { veryComplicated } from "./mycomponent.svelte"
test('it works', async () => {
expect(vercomplicated("foo").toBe("bar"))
})
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?
Upvotes: 4
Views: 1780
Reputation: 4516
Found it. I had to call render
.
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>
Upvotes: 4
Reputation: 4710
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
Upvotes: 3