测试库-测试依赖CSS的逻辑



我制作了这个组件,它所做的一切都是接收文本(长段落(,如果它在lines道具上,CSS将截断文本。如果被截断,则会有一个"全部显示"按钮,该按钮将删除隐藏部分文本的类。

组件本身工作得很好,但想要测试它,除了练习测试之外,没有其他原因。

我写了一个测试:

import { render, fireEvent } from '@testing-library/vue';
import TruncateText from '../TruncateText.vue';
describe('TruncateText', () => {
it('should have truncate class on mount', async () => {
const text = 'Super Duper Long Text';
const { getByText } = render(TruncateText, { props: { text } });
const pTag = getByText(text);
expect(pTag).toHaveClass('truncate');
expect(pTag).toHaveTextContent(text);
});
it('container should be truncated', async () => {
const text =
'Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt';
const lines = 2;
const { getByText } = render(TruncateText, {
props: { text, lines },
});
expect(lastThreeCharacters).toBe('...');
});
});

关于如何编写测试以检查某些文本是否会被截断,有什么想法吗?

其他潜在的测试正在模拟click发射,这样我就可以检查类是否被删除了。这对于这个组件来说应该已经足够了。

<template>
<div>
<p
class="text truncate"
ref="announcement"
:style="truncated ? `-webkit-line-clamp:${lines}` : ''"
>
{{ text }}
</p>
<OBButton
:text="$t('show-all')"
class="show-all-button"
size="x-small"
v-if="truncated"
@click="showAll"
/>
</div>
</template>
<script>
export default {
props: {
text: {
type: String,
required: true,
},
lines: {
type: Number,
default: 10,
},
},
data() {
return { truncated: false };
},
mounted() {
this.truncated = this.isOverflown(this.$refs.announcement);
},
methods: {
isOverflown(el) {
return el.scrollHeight > el.clientHeight || el.scrollWidth > el.clientWidth;
},
showAll() {
this.$refs.announcement.classList.remove('truncate');
this.truncated = false;
},
},
};
</script>
<style lang="scss" scoped>
.text {
white-space: pre-line;
}
.truncate {
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
max-height: 24rem; //hack for IE1
}
.show-all-button {
margin-top: 1rem;
}
</style

通过查看组件,您可以在单击按钮时完成两件事:

  • 从段落中删除truncate
  • 将CCD_ 4属性设置为CCD_

我会使用:class="{ truncate: truncated }"将类绑定到属性,然后唯一需要测试onclick的是truncated已设置为false(您不想测试Vue是否有效(
这消除了showAll从段落中手动删除类的需要:Vue是数据驱动的=>当您更改数据时,Vue会相应地管理DOM。


为了尽可能清楚:您应该只测试组件的逻辑,而不测试其他内容。您没有测试Vue、JavaScript或浏览器。你相信这些工作(其他人负责为他们编写测试(。所以,按顺序:

  • 期望truncated在安装时具有适当的值(有效地测试isOverflown()在您关心的每种情况下都能提供预期的输出(
  • truncatedtrue时,在按钮上触发click(当truncatedtrue时,无需期望按钮存在,因为您将测试v-if是否工作(。单击按钮后,在$nextTick()中,期望truncated设置为false

下面是你不应该测试的东西的列表:

  • JavaScript的工作原理
  • Vue工作(应用:class:style,应用v-if等(
  • 浏览器理解并应用-webkit-line-clamp
  • 你的测试库工作
  • 单击按钮后showAll已经运行(如果单击按钮将truncated设置为false,则您希望能够重命名该方法,并且您的测试应该仍然通过(

就这样。

最新更新