所以我想测试一个使用React的上下文api的组件,它不起作用。它看起来应该很简单-如此处(React js - How to mock Context when testing component)所述,您要做的就是这样:
const context = { name: 'foo' };
const wrapper = mount(<SimpleComponent />, { context });
但是,我有一些非常相似的东西,而且似乎还没有发现。
这是我的测试文件-
import * as React from 'react'
import Enzyme, { shallow, mount } from "enzyme";
import Home from '../pages/home/index'
import Adapter from "enzyme-adapter-react-16";
import stateVals from '../__mocks__/stateVals';
console.log('value of stateVals: ', stateVals)
describe('Pages', () => {
describe('Index', () => {
it('should render without throwing an error', function () {
const wrap = mount(<Home/>, { stateData: { state: stateVals } })
expect(wrap.find('div').text()).toBe('hello there main home')
})
})
})
这是我导入的stateVals对象:
const stateVals = {
ContextNext: "ldjkfs",
route: "/home",
styledcomponent: "sfsdfsdfsdf",
name: "dfasfasfasdf",
renderCloseAbout: false,
aboutCardStatus: "closed",
uploadedHistory: null,
greptchaTime: Date.now(),
loginStatus: "initial",
registrationStatus: "N/A",
userEmail: "N/A",
completeRegistration: {},
pageVal: "",
addPurchaseSubsJSON: ["empty"],
admins: ['SUPERDOOPERSECRET'],
modal: {
open: false,
message: ''
}
}
export default stateVals
这是我要测试的组件的开头-
class Home extends Component {
render(){
return(
<MainContext.Consumer>
{stateData => {
return(
<div className='grid-container abspos'>
{renderIf(stateData.state.modal.open==true)(
<Modal/>
)}
它引发此错误:
TypeError: Cannot read property 'state' of undefined
26 | return(
27 | <div className='grid-container abspos'>
> 28 | {renderIf(stateData.state.modal.open==true)(
| ^
29 | <Modal/>
30 | )}
为什么会这样呢?
编辑:
这也行不通:
import * as React from 'react'
import Enzyme, { shallow, mount } from "enzyme";
import Home from '../pages/home/index'
import Adapter from "enzyme-adapter-react-16";
import stateVals from '../__mocks__/stateVals';
console.log('value of stateVals: ', stateVals)
let context = {state: stateVals }
console.log('value of context: ', context)
describe('Pages', () => {
describe('Index', () => {
it('should render without throwing an error', function () {
const wrap = mount(<Home/>, context )
expect(wrap.find('div').text()).toBe('hello there main home')
})
})
})
也不是;
const wrap = mount(<Home/>, {context: stateVals})
也不使用这个:
const wrap = mount(<Home/>, {context: {stateData: stateVals}})
也没有:
const wrap = mount(<Home/>, {context: {stateData: {state: stateVals}}})
也不是;
const wrap = mount(<Home/>, {stateData: stateVals})
最佳答案
答案是包装提供程序,因为上下文api尚未完成。谢谢spenguin!
import * as React from 'react'
import Enzyme, { shallow, mount } from "enzyme";
import Home from '../pages/home/index'
import Adapter from "enzyme-adapter-react-16";
import { Provider } from '../services/Context/Provider'
import stateVals from '../__mocks__/stateVals';
describe('Pages', () => {
describe('Index', () => {
it('test ', function () {
const wrap = mount(<Provider value={{stateVals}}><Home/></Provider>)
expect(wrap.find('#maintext').text()).toBe('hello there main home')
})
})
})