reactjs - 获取 Jest 和 Enzyme 中连接组件的状态

标签 reactjs unit-testing testing redux jestjs

大家好!假设我有这个组件类:

@connect(
  state =>({
    someState: state.oneLevel.response
  })
)
export default class SomeClass extends React.Component{
constructor(props){
  super(props)
  this.state ={
    someState: [],
    isLoading: false,
    isLoaded: false
  }
}
}

该组件与 superagent 进行异步调用

componentDidMount(){
 var url = 'someapi.com/somedatatofetch'
 this.setState({isLoading: true})
 request.get(url)
 .set('some headers 1', 'somevalue')
 .set('some headers 2', 'somevalue')
 .then((success) => {
      this.setState({
        isLoading: false,
        isLoaded: true
      })
 })
}

现在我被分配为此组件编写一个单元测试,以检查它是否已成功更改其状态。我使用 Jest 作为我的测试框架和处理 DOM 渲染器等的 enzyme 。

describe("Network Functionality", ()=>{
  const wrapper = mount(<Provider store={store}><SomeComponent /><Provider>)
  
  it("Should change the isLoaded state to true", ()=>{
    const expectedState = true
    //mocking with supertest
    return mockApi().get('testapi.com/someroute')
    .set('some-headers1', 'somevalue')
    .set('some-headers2', 'somevalue')
    .then((success) => {
    expect(wrapper.state(isLoaded)).toEqual(expectedState)
    })
  }
})

使用该代码,响应如下: 类型错误:无法读取 null 的属性“isLoaded”

我的问题是,有没有办法使用连接的组件获取状态? 我尝试将组件导出为 ConnectedComponents 和 {Components} 它工作完美,但我想使用连接的组件。

为什么我要使用连接的组件?因为我的应用程序的每个组件都是使用此方案构建的,并且导出为 ConnectedComponents 和 {Components} 是不可行的,因为我的应用程序中有如此多的组件,这可能会导致更多问题

最佳答案

我已经通过使用查找 Node 组件来解决这个问题 wrapper.find('SomeComponent') 如果您 console.log() 它,您将看到它将生成组件节点以及状态。这是我的最终代码

describe("Network Functionality", ()=>{
  const wrapper = mount(<Provider store={store}><SomeComponent /><Provider>)
  
  it("Should change the isLoaded state to true", ()=>{
    const expectedState = true
    var somecomponent = wrapper.find("SomeComponent")
    //mocking with supertest
    return mockApi().get('testapi.com/someroute')
    .set('some-headers1', 'somevalue')
    .set('some-headers2', 'somevalue')
    .then((success) => {
    expect(somecomponent.getNode().state.isLoaded)toEqual(expectedState)
    
    })
  }
})
如您所见,我正在创建另一个变量来包含 SomeComponent 搜索结果。最后,我调用 getNode() 函数来获取 SomeComponent 及其状态。 我不知道这是否是最佳实践,但它确实有效。如果有更好的方法,我希望得到一些反馈

关于reactjs - 获取 Jest 和 Enzyme 中连接组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44426761/

相关文章:

reactjs - React-Admin 中的受控 TextInput

ios - 在模拟器中注销 Appstore

testing - 这是面试软件测试员时要问的一个很好的面试问题吗?

javascript - d3 v4 + React + es6 + crossfilter : Selection. exit().remove() 不起作用

reactjs - 如何在 yii2.0 中使用 React js

reactjs - 如何制作从 Ghost (Content API) 到 Next.js 的响应式图像?

c# - 单元测试调用 wcf 服务的方法

java - org.mockito.exceptions.misusing.InvalidUseOfMatchersException 有效表达式

python - 如何在单元测试期间在 Django RequestFactory 中设置消息传递和 session 中间件

laravel - 如果您在使用 Laravel 的测试环境中,是否有一种默认情况下模拟 API 请求的方法?