如何使用赛普拉斯访问React组件的本地状态?

问题描述 投票:1回答:1

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

我试过了

cy.get('.simple-component').its('getState')

要么

cy.get('.simple-component').invoke('getState')

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

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导出简单组件末尾的本地组件状态吗?

reactjs redux state invoke cypress
1个回答
1
投票

有一个赛普拉斯插件,称为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!')
  })
})
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.