CSS模块的类ID是否保持不变?

huangapple go评论54阅读模式
英文:

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 &lt;h1 data-test=&quot;my-hello&quot;&gt;Hello, {props.name}&lt;/h1&gt;;      // data-test id here
}

const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));
const element = &lt;Welcome name=&quot;Sara&quot; data-test=&quot;my-hello&quot; /&gt;;    // not here
root.render(element);

Test

cy.get(&#39;[data-test=&quot;my-hello&quot;]&#39;)
  .should(&#39;have.text&#39;, &#39;Hello, Sara&#39;)

huangapple
  • 本文由 发表于 2023年6月15日 18:36:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76481658.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定