英文:
Do CSS module class ID's stay constant?
问题
CSS模块将ID添加到类名中,例如classUc8xi
。
由于我们想要使用Cypress来定位某些元素,它使用某种QuerySelector,我想知道这些ID是否会发生变化?它们是否对每个用户都是恒定且相同的?
将这些ID添加到我们的Cypress测试中是否是一个好主意,就像下面这样,还是有更好的选择?
selectBtn: '[class="select-buttonUc8xi"]'
英文:
CSS modules add ID's to the classes e.g. classUc8xi
.
Since we want to target some elements with Cypress which uses some sort of QuerySelector, I want to know if these ID's ever change? Are they constant and identical for every user?
Is it a good idea to add these ID's to our Cypress tests like below or are there better options?
selectBtn: '[class="select-buttonUc8xi"]'
答案1
得分: 4
Uc8xi
的目的是将 CSS 限定在特定组件内,即防止一个组件的 CSS 影响到另一个相似的组件。
后缀字符可能是随机生成的,所以不要将该类用作选择器。
要么添加非模块 CSS(它不会有后缀),要么明确添加一个 data-test
属性来替代使用。
请注意,某些 React 组件可能不会将 data-test
传递到 HTML 页面,您可能需要将其添加到在组件上呈现的最顶层 "具体" 元素。
例如:
function Welcome(props) {
return <h1 data-test="my-hello">Hello, {props.name}</h1>; // 这里使用 data-test ID
}
const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" data-test="my-hello" />; // 不要在这里使用
root.render(element);
测试
cy.get('[data-test="my-hello"]')
.should('have.text', 'Hello, Sara')
英文:
The purpose of the Uc8xi
is to scope the CSS to that particular component, i.e to stop CSS from one component from "bleeding" to another similar component.
The suffix chars is likely to be generated somewhat randomly, so no don't use that class as a selector.
Either add non-module CSS (it won't have a suffix), or explicitly add a data-test
attribute to use instead.
Note that some React components won't pass the data-test
on to the HTML page, you might have to add it to the topmost "concrete" element that renders on the component.
For example:
function Welcome(props) {
return <h1 data-test="my-hello">Hello, {props.name}</h1>; // data-test id here
}
const root = ReactDOM.createRoot(document.getElementById('root'));
const element = <Welcome name="Sara" data-test="my-hello" />; // not here
root.render(element);
Test
cy.get('[data-test="my-hello"]')
.should('have.text', 'Hello, Sara')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论