【发布时间】:2019-07-05 15:13:33
【问题描述】:
所以我想测试一个使用 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})
【问题讨论】:
标签: reactjs unit-testing testing jestjs enzyme