英文:
vitest and svelte component's onMount
问题
I'm trying to use Svelte to create a simple reactive component. The component loads data from an api server onMount
and updates a reactive value (which updates an HTML element).
I have a simple vitest that renders the component and verifies the value of the HTML element. However, while running under vitest, the onMount
is never called, and hence the API call is never made. What am I missing?
Component.svelte
:
<script>
import { onMount } from 'svelte';
export let name = 'world';
onMount(async () => {
console.log('chat onMount event!');
const response = await fetch('http://localhost:8081/api');
// for this example, assume name returned by API is FOO
name = data.name;
});
</script>
<div id="#element">
<b> Hello {name}</b>
</div>
index.test.js
:
import { expect, test } from 'vitest';
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/svelte';
import Component from '../src/lib/Component.svelte';
test('should render', () => {
render(Component);
const heading = screen.getByText('Hello FOO');
expect(heading).toBeInTheDocument();
});
(Note: I have corrected the code by removing HTML encoding from the script tags.)
英文:
I'm trying to use Svelte to create a simple reactive component. The component loads data from an api server onMount
and updates a reactive value (which updates a html element).
I have a simple vitest that renders the component and verifies the value of the html element. However while running under vitest the onMount
is never called and hence the api call is never made. What am I missing ?
Component.svelte
:
<script>
import { onMount } from 'svelte';
export let name = 'world';
onMount(async () => {
console.log('chat onMount event!');
const response = await fetch('http://localhost:8081/api');
// for this example, assume name returned by api is FOO
name = data.name;
});
</script>
<div id="#element">
<b> Hello {name}</b>
</div>
index.test.js
:
import { expect, test } from 'vitest';
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/svelte';
import Component from '../src/lib/Component.svelte';
test('should render', () => {
render(Component);
const heading = screen.getByText('Hello FOO');
expect(heading).toBeInTheDocument();
});
答案1
得分: 3
"在一些调查后,我偶然发现了这个问题:https://github.com/vitest-dev/vitest/issues/2834
由于我正在运行 Svelte 4.0.0,所以在 vitest 下 onMount
不再被调用,因此我不得不将以下内容添加到 vite.config.js
以使其工作:
{
test: {
alias: [{ find: /^svelte$/, replacement: 'svelte/internal' }],
....
},
....
}
```"
<details>
<summary>英文:</summary>
After some sleuthing I stumbled on this issue: https://github.com/vitest-dev/vitest/issues/2834
As I'm running Svelte 4.0.0 the `onMount` is no longer invoked under vitest, hence I had to ad this to `vite.config.js` to make it work:
{
test: {
alias: [{ find: /^svelte$/, replacement: 'svelte/internal' }],
....
},
....
}
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论