英文:
Confusion about Unittesting with Vitest, while only having +page.svelte files
问题
为了我的大学作业,我需要学习在Svelte项目中使用Vitest进行测试。到目前为止,我已经了解了基础知识,并且能够编写基本的测试。现在,我需要测试我的同事在Svelte中编写的代码。问题是,如果我只有+page.svelte文件,我不太清楚到底需要导入什么东西来测试特定的函数。
例如,使用以下代码:
import footer from "../src/routes/+layout.svelte";
describe("Layout Test", () => {
test("that footer is being rendered", () => {
const host = document.createElement('div');
document.body.appendChild(host);
const instance = new footer({target: host});
expect(instance).toBeTruthy();
});
我得到了一个通过的测试。这个测试是否实际上测试了页脚是否存在,还是我误解了什么?它甚至是否测试了+layout.svelte页面上的页脚?
非常感谢任何帮助 <3
尝试研究这个问题,期望它能解决我的问题,但我找到的任何来源都没有帮助。
英文:
For my university work I need to learn Testing using Vitest in a Svelte Project. So far I understand the basics and was able to write basic tests. Now I need to test the code written by my colleagues in Svelte. The Problem is that I don't really know what exactly to import, if all I have are +page.svelte files. What do I need to import to test a specific function?
For example using:
import footer from "../src/routes/+layout.svelte";
describe("Layout Test", () => {
test("that footer is being rendered", () => {
const host = document.createElement('div');
document.body.appendChild(host);
const instance = new footer({target: host});
expect(instance).toBeTruthy();
});
I get a passed test. Did this actually test if the footer exists or am I misunderstanding something? Did it even test the footer from the +layout.svelte page?
Any help is greatly appreciated <3
Tried researching the problem, expected it to solve my question, but no source i found helped.
答案1
得分: 0
如果你想测试组件,你可以使用 Svelte Testing Library 与 vitest 结合使用。
你可以在 "示例" 部分找到示例,但基本上,你应该使用 "render" 函数来渲染组件,并通过 test-id 或文本等方式获取特定元素(查看 coreApi -> queries)。
在你的情况下,我会这样做:
import { render } from '@testing-library/svelte';
import { describe, it, expect } from 'vitest';
import footer from "../src/routes/+layout.svelte";
describe("Layout Test", () => {
it("渲染页脚", () => {
const { getByTestId } = render(footer);
expect(getByTestId('footer')).toBeTruthy();
});
});
注意:如果你想使用 "getByTestId" 查询,请记得为你的页脚添加一个 "data-testid"。
英文:
If you want to test components, you can use Svelte Testing Library in combination with vitest.
You can find examples in the "Example" section but basically, you should render components using the "render" function and you get specific elements by test-id or text, etc... (Check the coreApi -> queries).
In your case, I would do:
<!-- Language: typescript -->
import { render } from '@testing-library/svelte';
import { describe, it, expect } from 'vitest';
import footer from "../src/routes/+layout.svelte";
describe("Layout Test", () => {
it("renders the footer", () => {
const { getByTestId } = render(footer);
expect(getByTestId('footer')).toBeTruthy();
});
});
Note: remember to add a "data-testid" to your footer if you wish to use the "getByTestId" query.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论