在Svelte中编写自定义指令的基本结构
- 定义指令:
在Svelte中,使用
const myDirective = (node, value) => { /* 指令逻辑 */ };
的形式定义指令。其中node
是应用指令的DOM节点,value
是传递给指令的值。例如:
<script>
const myHighlight = (node, color) => {
node.style.backgroundColor = color;
return {
destroy() {
node.style.backgroundColor = '';
}
};
};
</script>
<div use:myHighlight="'yellow'">This text will be highlighted</div>
- 在上述例子中,
myHighlight
指令接收一个DOM节点node
和颜色值color
,并将节点的背景颜色设置为该颜色。返回的对象中的destroy
函数会在指令被移除时执行,这里是将背景颜色重置。
编写针对自定义指令的测试
- 使用测试框架:推荐使用
jest
和svelte - test - utils
。首先安装依赖:npm install --save - dev jest @testing - library/svelte
。
- 测试指令功能:
import { render } from '@testing-library/svelte';
import MyComponent from './MyComponent.svelte';
describe('MyDirective', () => {
it('should apply the directive correctly', () => {
const { container } = render(MyComponent);
const targetNode = container.querySelector('div');
expect(targetNode.style.backgroundColor).toBe('yellow');
});
});
- 上述测试代码渲染了包含自定义指令的组件
MyComponent
,然后检查应用指令的DOM节点的背景颜色是否正确设置。
- 测试指令的清理:
import { afterEach, describe, expect, it } from '@jest/globals';
import { render } from '@testing-library/svelte';
import MyComponent from './MyComponent.svelte';
describe('MyDirective', () => {
let container;
beforeEach(() => {
const { container: c } = render(MyComponent);
container = c;
});
afterEach(() => {
// 模拟指令移除
container.innerHTML = '';
const targetNode = container.querySelector('div');
expect(targetNode).toBeNull();
// 如果有清理逻辑,可进一步检查相关样式是否恢复
});
it('should clean up correctly', () => {
const targetNode = container.querySelector('div');
expect(targetNode.style.backgroundColor).toBe('');
});
});
- 在这个测试中,通过
afterEach
钩子模拟指令移除(这里通过清空容器HTML),并检查节点是否被移除以及清理逻辑是否正确执行(如背景颜色是否恢复默认)。这样的测试结构使得测试在不同场景下都能保证指令的正确性,并且具有较好的维护性,通过模块化的测试用例,方便在指令逻辑改变时进行针对性的调整。