gpt4 book ai didi

reactjs - 我如何 Jest 测试使用上下文 api 的 react 组件?

转载 作者:行者123 更新时间:2023-11-28 21:35:37 25 4
gpt4 key购买 nike

我的问题是:

  • 我使用 React 的上下文 API <StateConsumer></StateConsumer>检索 value.connected知道我的是否已连接。我想使用 jest 来模拟连接的用户。

我的代码是:

    import React, { Component } from 'react';
import SignPage from '../Connection/SignPage';
import OgdpcQuery from '../Ogdpc/OgdpcQuery/OgdpcQuery';
import {StateConsumer} from '../../api/context';

export default class Landing extends Component {

render() {

return (
<StateConsumer>
{(value) => {
if (value.connected === false){
return (
<div className="container">
<div className="row">
{/* State information on the profile */}
<SignPage/>
</div>
<div className="row">
{/* component who ll come to display login of each PS invitation */}
{/* <OgdpcRequest/> */}
</div>
</div>
)}
else if(value.connected === true){
return (
<div className="container">
<h1>connected</h1>
</div>
)
}
}}
</StateConsumer>
)
}
}

我想开个 Jest 做个测试:

如果我想让这个语句被验证,则以下语句 (value.connected) 为假 expect(wrapper).to.contain(<SignPage/>)

我试过这段代码来理解 jest 是如何工作的。我不知道如何测试上面的代码(我的登陆组件):

import {expect} from 'chai';
import React from 'react';
import {shallow} from 'enzyme';
import Landing from '../component/Landing/Landing';
import {StateConsumer} from '../api/context';

describe('<Landing />', () => {

let wrapper;
beforeEach(() => { wrapper = shallow(<Landing />, {context: true})})

const ContextConsumer = <ContextConsumer connected={true}/>

it('Test to look if something insine <Landing />', () => {
console.log('wrapper ===> ', wrapper.debug({ ignoreProps: true }));
expect(wrapper).to.contain(<SignPage/>);
})

}
)

我的应用程序充满了这样的东西,所以我无法前进。

我读了很多文档,但我并不真正理解它是如何工作的! Jest 起初对我来说真的很难看,init mock 和 fake function 对我来说看起来很奇怪。我想几周后这对我来说会更明显!所以如果你有一些建议,文档非常不稳定的新手或帮助它会很棒

如果这篇文章因为我的英语或公式看起来很糟糕,我很抱歉。谢谢!

最佳答案

好的,我找到了适合我的案例的解决方案:

describe('<Landing />', () => {
it('Test to look if something inside <Landing />', () => {
const wrapper = mount(
<StateProvider>
<Landing />
</StateProvider>
);
wrapper.setState({connected : false});
expect(wrapper).to.contain(<SignPage/>);
}
)

使用 wrapper.setState({connected : false}); 我能够将本地状态设置为“false”并模拟页面上未连接的用户并检查我的 SignPage 组件是否那里。

我不知道这是否是最好的方法,但对我来说它工作正常。

关于reactjs - 我如何 Jest 测试使用上下文 api 的 react 组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59102061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com