如何用 jest 测试 svelte 组件的功能?
How to test a function from a svelte component with jest?
网上有很多关于用jest测试svelte组件、调用渲染函数和模拟浏览器事件的文档。这很好,但是我如何在 svelte 组件中测试函数?
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"))
})
开玩笑
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.
在 veryComplicated
定义之前添加 export
没有帮助。
如何测试 veryComplicated
功能?
找到了。我不得不打电话给 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")
})
并且需要导出veryComplicated
函数。
您可以使用模块上下文脚本块导出函数。
<script context="module">
export veryComplicated() {
// ...
}
</script>
<div>...</div>
然后你就可以import { veryComplicated } from './mycomponent.svelte'
像你最初想做的那样了。
网上有很多关于用jest测试svelte组件、调用渲染函数和模拟浏览器事件的文档。这很好,但是我如何在 svelte 组件中测试函数?
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"))
})
开玩笑
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.
在 veryComplicated
定义之前添加 export
没有帮助。
如何测试 veryComplicated
功能?
找到了。我不得不打电话给 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")
})
并且需要导出veryComplicated
函数。
您可以使用模块上下文脚本块导出函数。
<script context="module">
export veryComplicated() {
// ...
}
</script>
<div>...</div>
然后你就可以import { veryComplicated } from './mycomponent.svelte'
像你最初想做的那样了。