捕获测试中的 React 警告

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

Catch React Warnings During Testing

问题

让我们考虑一下这个来自React文档的示例

const people = [
  'Creola Katherine Johnson: mathematician',
  'Mario José Molina-Pasquel Henríquez: chemist',
  'Mohammad Abdus Salam: physicist',
  'Percy Lavon Julian: chemist',
  'Subrahmanyan Chandrasekhar: astrophysicist'
];

export default function List() {
  const listItems = people.map(person =>
    <li>{person}</li>
  );
  return <ul>{listItems}</ul>;
}

当渲染这个组件时,React会在控制台中输出以下内容:

警告:列表中的每个子元素都应该有一个唯一的“key”属性。

我想确保我的组件不会出现这个问题。是否有一种方法可以使用Cypress(或其他工具)来检查React是否引发了这个警告?

英文:

Let's consider this example from the React docs:

const people = [
  &#39;Creola Katherine Johnson: mathematician&#39;,
  &#39;Mario Jos&#233; Molina-Pasquel Henr&#237;quez: chemist&#39;,
  &#39;Mohammad Abdus Salam: physicist&#39;,
  &#39;Percy Lavon Julian: chemist&#39;,
  &#39;Subrahmanyan Chandrasekhar: astrophysicist&#39;
];

export default function List() {
  const listItems = people.map(person =&gt;
    &lt;li&gt;{person}&lt;/li&gt;
  );
  return &lt;ul&gt;{listItems}&lt;/ul&gt;;
}

When rendering this component, React will write the following to the console:

> Warning: Each child in a list should have a unique "key" prop.

I want to ensure that my components do not exhibit this problem. Is there a way to check with Cypress (or another tool) that React has not raised this warning?

答案1

得分: 2

替换内置窗口方法如prompt ,您可以监视或存根应用程序窗口上的warn方法。

在此示例中,我还使用了一个别名来跟踪调用,然后在测试结束时检查调用计数。

cy.visit('/', {
  onBeforeLoad(win) {
    cy.spy(win, 'warn').as('warnings')
  },
})

// 运行测试

cy.get('@warnings').should('not.be.called')
英文:

From Replace built-in window methods like prompt, you can spy or stub the warn method on the app's window.

In this example, I also used an alias to track the calls, then check the call count at the end of the test.

cy.visit(&#39;/&#39;, {
  onBeforeLoad(win) {
    cy.spy(win, &#39;warn&#39;).as(&#39;warnings&#39;)
  },
})

// run the test

cy.get(&#39;@warnings&#39;).should(&#39;not.be.called&#39;)

huangapple
  • 本文由 发表于 2023年2月26日 23:11:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572911.html
匿名

发表评论

匿名网友

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

确定