我正在使用 redux 进行 react 并使用 cypress 进行测试,
我能够使用
cy.window().its('store').invoke('getState').then((state) => {}
但是我如何访问组件的本地状态而不是应用程序商店?
我试过
cy.get('.simple-component').its('getState')
或者
cy.get('.simple-component').invoke('getState')
但 Cypress 正在返回“CypressError:重试超时:cy.invoke() 出错,因为属性:'getState' 在您的主题上不存在”
在 Cypress 控制台(在 chrome 中)上,它正在发出:
Yielded:
<div class="simple-component" getstate="[object Object]"></div>
这似乎是由 React 从 DOM 中删除方法造成的,所以我需要在 React 中而不是在 DOM 中访问它?
import React, { Component } from 'react';
class simpleComponent extends Component {
constructor(props) {
super(props)
this.state = {
sample: "hello"
}
}
// getState() just for testing on cypress
getState() {
return this.state
}
render(){
return <div className="simple-component" getState={this.getState()}></div>
}
}
作为替代方案,我可以使用 window.store 在简单组件的末尾导出本地组件状态吗?
最佳答案
>= 7.0.0 版
从 Cypress 7.0 开始,新的 Component Test Runner 现在与 Cypress 捆绑在一起
来自 https://www.cypress.io/blog/2021/04/06/cypress-component-testing-react:
我们仍然需要安装 react 适配器来挂载组件:
yarn add -D cypress @cypress/react @cypress/webpack-dev-server
将匹配您的组件测试的 glob 模式添加到 cypress.json
:{
"component": {
"testFiles": "**/*.test.{js,ts,jsx,tsx}",
"componentFolder": "src"
}
}
告诉 Cypress 使用 @cypress/webpack-dev-server 进行组件测试。在 cypress/plugins/index.js
:const injectDevServer = require("@cypress/react/plugins/react-scripts")
module.exports = (on, config) => {
injectDevServer(on, config)
return config
}
这会将 Cypress Webpack Dev Server 配置为使用与 Create React App 相同的 Webpack 配置。如果您使用不同的模板,例如 Next.js,我们还有其他一些可用的适配器。也可以创建自己的适配器。
< 7.0.0 版
有一个 Cypress 插件,名为
react-unit-test
.它使您能够挂载 React
直接访问组件(添加 cy.mount()
命令)并提供对组件内部状态的访问。这是 repo 的自述文件中的一个示例:
// load Cypress TypeScript definitions for IntelliSense
/// <reference types="cypress" />
// import the component you want to test
import { HelloState } from '../../src/hello-x.jsx'
import React from 'react'
describe('HelloState component', () => {
it('works', () => {
// mount the component under test
cy.mount(<HelloState />)
// start testing!
cy.contains('Hello Spider-man!')
// mounted component can be selected via its name, function, or JSX
// e.g. '@HelloState', HelloState, or <HelloState />
cy.get(HelloState)
.invoke('setState', { name: 'React' })
cy.get(HelloState)
.its('state')
.should('deep.equal', { name: 'React' })
// check if GUI has rerendered
cy.contains('Hello React!')
})
})
关于reactjs - 如何使用 Cypress 访问 React 组件本地状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55349463/