Javascript 访问组件&x27;s苗条道具用于玩笑测试
问题:如何使用jest测试访问苗条组件的道具。例如,如果苗条组件如下所示: 示例组件。苗条Javascript 访问组件&x27;s苗条道具用于玩笑测试,javascript,testing,jestjs,svelte,svelte-component,Javascript,Testing,Jestjs,Svelte,Svelte Component,问题:如何使用jest测试访问苗条组件的道具。例如,如果苗条组件如下所示: 示例组件。苗条 <script> import { createEventDispatcher } from 'svelte' const dispatch = createEventDispatcher() export let booleanProp const toggle = () => { dispatch('toggle')
<script>
import { createEventDispatcher } from 'svelte'
const dispatch = createEventDispatcher()
export let booleanProp
const toggle = () => {
dispatch('toggle')
}
</script>
<style lang="scss" src="./style.scss">
</style>
<button class:-closed="{booleanProp == false}" class="c-toggle" on:click={toggle}>
<svg class="toggle-icon">
{#if booleanProp}
<use xlink:href="icons/some-icon.svg" />
{:else}
<use xlink:href="icons/some-other-icon.svg" />
{/if}
</svg>
</button>
从“svelte”导入{createEventDispatcher}
const dispatch=createEventDispatcher()
导出let booleanProp
常量切换=()=>{
分派('切换')
}
{#if booleanProp}
{:else}
{/if}
属性是与外部世界的接口。嘲弄它:
示例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();
});
好文章:
示例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)
})
要捕获元素,您需要一个aria标签来标识它:
<button aria-label="toggle-boolean-prop" class:-closed="{booleanProp == false}" class="c-toggle" on:click={toggle}>...</button>
。。。
因此,就像一个简单的测试用例一样,我有一个细长的文件,其中有一个布尔属性,如果值与每个按钮单击事件切换,则需要检查该属性。我现在更新我的问题,让您对确切的用例有更多的了解。谢谢您的回复。:)这不是道具的行为。一个特殊的函数应该处理业务逻辑。这应该在一个单独的测试中进行测试,测试这个函数是否转换了一个值。我想你应该测试功能性,而不是实现。这是正确的。我看过你发布的示例,但正如你所看到的,我的示例svelte文件有点不同。有没有一种可能的方法可以通过点击按钮的fireEvent来检查或模拟布尔属性的功能?我想您正在使用测试库查看示例3。
<button aria-label="toggle-boolean-prop" class:-closed="{booleanProp == false}" class="c-toggle" on:click={toggle}>...</button>