我是Jest的新手,我只想从我拥有的组件中获取状态。如果组件不使用material-ui并且不使用'withStyles'导出,则可以获取状态。但是当我使用'withStyles'导出组件时,它突然不起作用。
零件:
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
//CSS styles
const styles = {
root: {
marginTop:25,
},
};
class Test extends React.Component{
constructor(props){
super(props);
this.state={
test: 'test'
}
}
render(){
const {classes} = this.props;
return(
<p className={classes.root}>test</p>
)
}
}
export default withStyles(styles)(Test);
测试:
test('Get state', () => {
const wrapper = mount(<Test classes={{}}/>);
expect(wrapper.state('test')).toEqual('test')
})
我阅读了material-ui文档,看到它们也提供了一种测试方法。但即使我使用他们的实现它也不起作用。
材料 - UI测试:
describe('<Test />', () => {
let shallow;
beforeEach(() => {
shallow = createShallow();
});
it('get state', () => {
const wrapper = shallow(<Test/>);
expect(wrapper.state('test')).toEqual('test')
});
});
我一直收到错误:
TypeError:ShallowWrapper :: state(“test”)要求
state
不是null
或undefined
谁知道我做错了什么?
如果为了测试目的而导出其他版本的类组件而不使用withStyles()
包装器,该怎么办?
如:export const TestComponent = new Text();
可以将其导入为:import { TestComponent } from './path';
我找到了一个解决方法,不知道这是不是正确的方法。但是您可以导出自己的类,而不是在测试文件中导入该类,然后您就可以获得该状态。
新组件:
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
//CSS styles
const styles = {
root: {
marginTop:25,
},
};
export class Test extends React.Component{
constructor(props){
super(props);
this.state={
test: 'test'
}
}
render(){
const {classes} = this.props;
return(
<p className={classes.root}>test</p>
)
}
}
export default withStyles(styles)(Test);
新测试:
import {Test} from '../components/TestApp';
test('Get state', () => {
const wrapper = mount(<Test classes={{}}/>);
expect(wrapper.state('test')).toEqual('test')
})
不要忘记添加classes={{}}
,否则jest会抱怨它无法识别您在组件中定义的className。
经过大量的迭代,我找到了一个可行的解决方案。
import React from 'react'
import { shallow, mount } from 'enzyme'
import { unwrap } from '@material-ui/core/test-utils'
import Component from 'path'
const UnwrappedComponent = unwrap(Component);
it('with shallow", () => {
const wrapper = shallow(<UnwrappedComponent classes={{}} />)
})
it("with mount", () => {
const wrapper = mount(<UnwrappedComponent classes={{}} />)
})