属性是与外部世界的接口。模拟它:
示例 1)模拟道具
test("should render articles", () => {
const booleanProp = " I am true";
const { container, getByText } = render(ExampleComponent, {
props: {
articles: [
{
booleanProp
}
]
}
});
expect(container.querySelector("a").href).toBe(
`http://localhost/${canonical_url}`
);
expect(getByText(myBool)).toBeInTheDocument();
});
好文章:https ://dev.to/jpblancodb/testing-svelte-components-with-jest-53h3
示例 2) 模拟 DOM
用于测试按钮后面的功能。HTML 代码具有让被调用函数完成其工作所需的元素:
it('testFunctionModifiesDom', async () => {
const documentHTML =
'<!doctype html><html><body>' +
'<my-custom-element>' +
'<input id="id0" value="true"/>' +.
'</my-custom-element>' +
'</body></html>';
document.body.innerHTML = documentHTML;
const myCustomElement = document.querySelector('my-custom-element');
let actual = myCustomElementsService.toggleMyBoolEffectsElement();
expect(myCustomElement.getElementById('id0').value).toBe(false)
})
示例 3)模拟组件。
使用@testing-library 检查按钮点击是否有动作:
import {render, fireEvent} from '@testing-library/svelte'
import {jest} from "@jest/globals";
it('testMyCustomElement_awesomeAction', async () => {
const config = {booleanProp: true};
const dom = render(MyCustomElement, config);
const toggleButton = dom.getByLabelText('toggle-boolean-prop');
await fireEvent.click(toggleButton);
expect(config.booleanProp).toBe(false);
})
要捕获元素,您需要一个 aria-label 来识别它:
<button aria-label="toggle-boolean-prop" class:-closed="{booleanProp == false}" class="c-toggle" on:click={toggle}>...</button>