英文:
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 = [
'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>;
}
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('/', {
onBeforeLoad(win) {
cy.spy(win, 'warn').as('warnings')
},
})
// run the test
cy.get('@warnings').should('not.be.called')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论