小编Oma*_*mar的帖子

如何使用 Cypress 访问 React 组件的本地状态?

我正在使用 redux 进行反应并使用 cypress 进行测试,我能够使用 cy.window().its('store').invoke('getState').then((state) => {} 但是我如何访问组件的本地状态而不是应用程序商店?

我试过

cy.get('.simple-component').its('getState')
Run Code Online (Sandbox Code Playgroud)

或者

cy.get('.simple-component').invoke('getState')
Run Code Online (Sandbox Code Playgroud)

但赛普拉斯正在返回“赛普拉斯错误:重试超时:cy.invoke() 出错,因为属性:'getState' 在您的主题上不存在”并且在赛普拉斯控制台上(在 chrome 中)它正在发出:

Yielded:   
<div class="simple-component" getstate="[object Object]"></div>
Run Code Online (Sandbox Code Playgroud)

这似乎是由 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>
    }    
}
Run Code Online (Sandbox Code Playgroud)

作为替代方案,我可以使用 window.store 在简单组件的末尾导出本地组件状态吗?

state invoke reactjs redux cypress

3
推荐指数
1
解决办法
6303
查看次数

标签 统计

cypress ×1

invoke ×1

reactjs ×1

redux ×1

state ×1