gpt4 book ai didi

javascript - 传递 React 浅 enzyme 测试用例的上下文 -jest

转载 作者:行者123 更新时间:2023-12-02 23:58:56 29 4
gpt4 key购买 nike

如何在辅助方法中传递上下文并提取数据?

请参阅以下代码片段:

import AppContext from '../../context/AppContext'
import extractDatta from '../../helper';

class App extends Component{
static contextType = AppContext

componentWillMount(){
const resolvedData = extractData("/home",this.context)
}

render(){
return(
)
}

}

helper/index.js:

const extractData = (path, context) => {
// getting context as undefined
}

应用程序.test.js:

describe('App test suites', () => {
let wrapper;
let appContext;
beforeEach(() => {
appContext = {name: "Application"}
wrapper = shallow(<Supplier />, { appContext })
})
it('Should render the App Component', () => {
expect(wrapper).toMatchSnapshot();
})
})

感谢任何帮助:)

最佳答案

因此,这是我在 Enzyme 团队努力完成[ https://github.com/airbnb/enzyme/issues/1553](React ]时的巧妙解决方法。 16 支持)。我在组件类上提供旧版 contextTypes,允许根据文档传递上下文。

import PropTypes from "prop-types";

describe('App test suites', () => {
let wrapper;
let appContext;
beforeEach(() => {
appContext = {name: "Application"}

// Hack in the legacy context API just for tests. You'll get a warning, but it
// ought to work...
Supplier.contextTypes = {
name: PropTypes.string
}

wrapper = shallow(<Supplier />, { appContext })
})

it('Should render the App Component', () => {
expect(wrapper).toMatchSnapshot();
})
})

关于javascript - 传递 React 浅 enzyme 测试用例的上下文 -jest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55256487/

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