我们使用 data-test-target 属性并在 JSX 中手动写入。
在简单版本中,这就是您所需要的。但是,如果您有复杂的案例,例如同一页面上具有相同字段的两个表单,则需要区分它们。
所以我们这样做:
目标可以由3个参数构建:
假设您有一个 React 组件并想要设置测试目标。
例如,您在组件中有 2 个按钮:删除和编辑,所以
它看起来像
<button data-test-target="component-name:remove">Remove</button>
<button data-test-target="component-name">Edit</button>
如果页面上有多个此组件,则应在 props 中传递上下文:
<button data-test-target="component-name:remove::todo-list">Remove</button>
我用来遵循这个想法的助手:
import dashify from 'dashify';
export const createTestAttribute = ({
block: blockPart,
element,
context,
}) => {
const elementPart = element ? `:${dashify(element)}` : '';
const contextPart = context ? `::${dashify(context)}` : '';
return `${blockPart}${elementPart}${contextPart}`;
};
用法:
<button
data-test-target={createTestAttribute({
block: 'component-name',
element: 'remove',
context: props.testContext,
})}
>
Remove
</button>
使用它的测试将是稳定的,它们不会依赖于您的标记结构和类名