大家好!假设我有这个组件类:
@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/